﻿namespace ImageProcessing
{

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Windows.Forms;
    using CustomControlTrial;
    using Forms;
    using MathWorks.MATLAB.NET.Arrays;
    using MathWorks.MATLAB.NET.Utility;
    using Microsoft.VisualBasic;
    using matlabRetinx;
    using ShapesLib;
    using System.Runtime.InteropServices;
    using System.Drawing.Printing;


    /// <summary>
    /// Main form's code.
    /// </summary>
    public partial class Main : Form
    {
        #region Members
        /// <summary>
        /// Editing Mode represent the editing mode 
        /// </summary>
        private static EditingMode enumMode = EditingMode.Nothing;

        /// <summary>
        /// A list of opened images.
        /// </summary>
        private static List<DImage> imageList = new List<DImage>();

        /// <summary>
        /// Sets the illumination settings to gamma.
        /// </summary>
        private static InputValuesEnum inputValueoper;

        /// <summary>
        /// Index of currently open image.
        /// </summary>
        private static int currImage = 0;

        /// <summary>
        /// To know selected index change in history listbox
        /// </summary>
        private static bool selectedIndexChange = false;

        /// <summary>
        /// Window that shows all opened pictures
        /// </summary>
        private static ToolStripMenuItem picWindows;

        /// <summary>
        /// Calculation form.
        /// </summary>
        private static CalculationForm calcFormObjec;

        /// <summary>
        /// Filter type for noise removal
        /// </summary>
        private static FilterType filterType;

        /// <summary>
        /// Instance of the main form
        /// </summary>
        private static Main instance;

        /// <summary>
        /// Operation name, used for history.
        /// </summary>
        private static string operationName = string.Empty;

        /// <summary>
        /// Histogram chart
        /// </summary>
        private static HistogramChart histoChart = new HistogramChart();

        /// <summary>
        /// Form current location
        /// </summary>
        private Point formLocation;

        /// <summary>
        /// size of the form
        /// </summary>
        private Size formSize;

        /// <summary>
        /// Start point
        /// </summary>
        private Point startformLocation;

        /// <summary>
        /// Starts form from size
        /// </summary>
        private Size startformSize;

        /// <summary>
        /// checks if form is moveable
        /// </summary>
        private bool canMove = false;

        /// <summary>
        /// Checks if window is minimized
        /// </summary>
        private bool isMinmize = false;

        /// <summary>
        /// X and Y coordinates for the form
        /// </summary>
        private int x, y;

        /// <summary>
        /// Border location
        /// </summary>
        private int border = -1;

        /// <summary>
        /// Form is maximized
        /// </summary>
        private bool maxmized = false;

        /// <summary>
        /// Form is resizable
        /// </summary>
        private bool canResize;

        private Thread videoThread;
        private int waitMS;
        private delegate void UpdateFrameTick();
        private event UpdateFrameTick UpdateFrameHandler;
        private bool canPause;
        private bool seek;

        Mutex mutex = new Mutex(false);
        PHTab HistogramTab;
        PHTab PhotoInfoTab;
        PHTab ChannelsTab;
        PHTab HistoryTab;
        int videoTrackCounter = 0;
        bool tracking = false;
        double trackValue = 0;
        PrintDocument printDoc;


        /// <summary>
        /// to save current in history view
        /// </summary>
        public static int currentInHistoryView;

        /// <summary>
        /// Border of the form
        /// </summary>
        private int formBorder;
        bool buzy = true;
        bool buzy2 = true;
        public static PHPictureStringList channels;
        public Panel HistogramPanel = new Panel();
        int delImage = 0;
        public static Panel ImagePanel;
        public static Cursor MainCursor;
        public static ImageInfo Info;
        #endregion

        /// <summary>
        /// Initializes a new instance of the Main class.
        /// </summary>
        public Main()
        {
            this.InitializeComponent();
            printDoc = new PrintDocument();
            printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
            MainCursor = this.Cursor;
            Info = new ImageInfo();
            this.CmbResizingAlgo.SelectedIndex = 0;
            this.CmbMappingMethod.SelectedIndex = 0;
            this.grbInputValues.Visible = false;
            this.phTabContainer3.Add("History");
            // this.phTabContainer3.tabs[0].Panel.Controls.Add(this.historyListBox);
            this.HistoryTab = this.phTabContainer3.tabs[0];
            this.HistoryTab.Panel.Controls.Add(this.phPictureStringList1);

            Control.CheckForIllegalCrossThreadCalls = false;

            this.historyListBox.Dock = DockStyle.Fill;
            this.phPictureStringList1.Dock = DockStyle.Fill;
            this.phTabContainer3.UpdateViewPanel();

            //  this.WindowState = FormWindowState.Maximized;
            //this.VerticalToolStrip.Visible = true;
            this.Btn_Subtract.Visible = true;
            instance = this;
            this.phTabContainer1.Dock = DockStyle.Fill;
            this.phTabContainer2.Dock = DockStyle.Fill;
            this.phTabContainer3.Dock = DockStyle.Fill;
            this.CenterTheForm();
            this.startformLocation = this.Location;
            this.startformSize = this.Size;
            this.phTabContainer2.Add("Histogram");
            this.HistogramTab = this.phTabContainer2.tabs[0];
            this.StartHistogram();

            // this.WindowState = FormWindowState.Maximized;
            this.MaximizeTheForm();
            this.phTabContainer1.ActiveTabIndexChanged += new CustomControlTrial.PHTabContainer.ActiveTabIndexHandler(this.PhTabContainer1_ActiveTabIndexChanged);
            this.phTabContainer2.ActiveTabIndexChanged += new CustomControlTrial.PHTabContainer.ActiveTabIndexHandler(this.PhTabContainer2_ActiveTabIndexChanged);
            this.phTabContainer3.ActiveTabIndexChanged += new CustomControlTrial.PHTabContainer.ActiveTabIndexHandler(phTabContainer3_ActiveTabIndexChanged);
            this.phTabContainer1.TabRemoved += new CustomControlTrial.PHTabContainer.TabRemovedHandler(phTabContainer1_TabRemoved);
            this.phTabContainer2.TabRemoved += new CustomControlTrial.PHTabContainer.TabRemovedHandler(phTabContainer2_TabRemoved);
            this.phTabContainer3.TabRemoved += new CustomControlTrial.PHTabContainer.TabRemovedHandler(phTabContainer2_TabRemoved);
            // for deleted tabs
            this.phTabContainer1.started = true;
            this.phTabContainer2.started = true;
            this.phTabContainer3.started = true;
            // this.buzy = false;
            // this.buzy2 = false;
            StartChannels();
            this.phTabContainer3.Add("Image Info");
            PhotoInfoTab = this.phTabContainer3.tabs[2];
            PhotoInfoTab.Panel.Controls.Add(Info.Panel);
            HistoryTab.SetActive();
            ImagePanel = phTabContainer1.tempPanel;

            UpdateFrameHandler += new UpdateFrameTick(Main_UpdateFrameHandler);
            waitMS = 40;
        }

        public static void UpdateImageInfo()
        {
            try
            {
                Info.Name = imageList[currImage].Name;
                Info.Height = imageList[currImage].Height.ToString();
                Info.Width = imageList[currImage].Width.ToString();
                Info.Path = imageList[currImage].FilePath;
                Info.Type = imageList[currImage].Extenstion;
                // Info.Comment=imageList[currImage].Comment;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        public void StartChannels()
        {
            channels = new PHPictureStringList();
            channels.Dock = DockStyle.Fill;
            channels.Checkable = true;
            channels.ActiveIndexChanged += new PHPictureStringList.ActiveIndexHandler(channels_ActiveIndexChanged);
            channels.CheckedChanged += new PHPictureStringList.CheckedChangedHandler(channels_CheckedChanged);
            phTabContainer3.Add("Channels");
            ChannelsTab = phTabContainer3.tabs[phTabContainer3.tabs.Count - 1];
            ChannelsTab.Panel.Controls.Add(channels);
            channels.Width = phTabContainer3.Width;
            PHPictureString s = new PHPictureString();
            s = new PHPictureString();
            s.Visible = false;
            s.Lbl_Text.Text = "RGB";
            channels.Add(s);
            s = new PHPictureString();
            s.Visible = false;
            s.Lbl_Text.Text = "R";
            channels.Add(s);
            s = new PHPictureString();
            s.Visible = false;
            s.Lbl_Text.Text = "G";
            channels.Add(s);
            s = new PHPictureString();
            s.Visible = false;
            s.Lbl_Text.Text = "B";
            channels.Add(s);
            buzy = false;
            channels.Select(0);
            //  phTabContainer3.UpdateViewPanel();
        }

        public static void UpdateChannelsPic()
        {
            try
            {
                channels.Dock = DockStyle.Fill;
                double[,] red, green, blue, zeros;
                red = new double[imageList[currImage].Height, imageList[currImage].Width];
                green = new double[imageList[currImage].Height, imageList[currImage].Width];
                blue = new double[imageList[currImage].Width, imageList[currImage].Height];
                zeros = new double[imageList[currImage].Height, imageList[currImage].Width];
                FourierOperations.SeparateColors(ref red, ref green, ref blue, imageList[currImage]);
                ((PHPictureString)channels.Controls[0]).Visible = true;
                ((PHPictureString)channels.Controls[1]).Visible = true;
                ((PHPictureString)channels.Controls[2]).Visible = true;
                ((PHPictureString)channels.Controls[3]).Visible = true;
                ((PHPictureString)channels.Controls[0]).Width = channels.Width - 2;
                ((PHPictureString)channels.Controls[1]).Width = channels.Width - 2;
                ((PHPictureString)channels.Controls[2]).Width = channels.Width - 2;
                ((PHPictureString)channels.Controls[3]).Width = channels.Width - 2;
                ((PHPictureString)channels.Controls[0]).Picture.Image = imageList[currImage].ImageBitmap;
                ((PHPictureString)channels.Controls[1]).Picture.Image = Operations.DisplayMatrix(FourierOperations.RecollectImage(zeros, zeros, blue, PostProcessing.None));
                ((PHPictureString)channels.Controls[2]).Picture.Image = Operations.DisplayMatrix(FourierOperations.RecollectImage(zeros, green, zeros, PostProcessing.None));
                ((PHPictureString)channels.Controls[3]).Picture.Image = Operations.DisplayMatrix(FourierOperations.RecollectImage(red, zeros, zeros, PostProcessing.None));

                if (channels.ActiveIndex == 0)
                {
                    ((PHPictureString)channels.Controls[1]).IsCheckedWithoutEvent(true);
                    ((PHPictureString)channels.Controls[2]).IsCheckedWithoutEvent(true);
                    ((PHPictureString)channels.Controls[3]).IsCheckedWithoutEvent(true);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

        }

        private void phTabContainer3_ActiveTabIndexChanged(object sender, EventArgs e)
        {
            try
            {
                foreach (Control c in channels.Controls)
                {
                    c.Width = phTabContainer3.tempPanel.Width - 5;
                }
                foreach (Control c in phPictureStringList1.Controls)
                {
                    c.Width = phTabContainer3.tempPanel.Width - 5;
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        private void channels_ActiveIndexChanged(object sender, EventArgs e)
        {
            if (channels.ActiveIndex == 0)
            {
                ((PHPictureString)channels.Controls[1]).IsCheckedWithoutEvent(true);
                ((PHPictureString)channels.Controls[2]).IsCheckedWithoutEvent(true);
                ((PHPictureString)channels.Controls[3]).IsCheckedWithoutEvent(true);
            }

            double[,] red, green, blue, zeros;
            red = new double[imageList[currImage].Height, imageList[currImage].Width];
            green = new double[imageList[currImage].Height, imageList[currImage].Width];
            blue = new double[imageList[currImage].Width, imageList[currImage].Height];
            zeros = new double[imageList[currImage].Height, imageList[currImage].Width];
            FourierOperations.SeparateColors(ref red, ref green, ref blue, imageList[currImage]);
            if (!channels.CheckedPics.Contains(1))
            {
                blue = zeros;
            }
            if (!channels.CheckedPics.Contains(2))
            {
                green = zeros;
            }
            if (!channels.CheckedPics.Contains(3))
            {
                red = zeros;
            }
            ((PictureBox)phTabContainer1.tempPanel.Controls[0]).Image = Operations.DisplayMatrix(FourierOperations.RecollectImage(red, green, blue, PostProcessing.None));
        }

        private void channels_CheckedChanged(object sender, EventArgs e)
        {
            if (channels.CheckedPics.Contains(0) && ((PHPictureString)sender).index == 0)
            {
                ((PHPictureString)channels.Controls[1]).IsCheckedWithoutEvent(true);
                ((PHPictureString)channels.Controls[2]).IsCheckedWithoutEvent(true);
                ((PHPictureString)channels.Controls[3]).IsCheckedWithoutEvent(true);
            }
            else if (channels.CheckedPics.Contains(1) && channels.CheckedPics.Contains(2) && channels.CheckedPics.Contains(3) && ((PHPictureString)sender).index != 0)
            {
                ((PHPictureString)channels.Controls[0]).IsCheckedWithoutEvent(true);
            }
            else if (channels.CheckedPics.Contains(0) && (!channels.CheckedPics.Contains(1) || !channels.CheckedPics.Contains(2) || !channels.CheckedPics.Contains(3)))
            {
                ((PHPictureString)channels.Controls[0]).IsCheckedWithoutEvent(false);
            }

            double[,] red, green, blue, zeros;
            red = new double[imageList[currImage].Height, imageList[currImage].Width];
            green = new double[imageList[currImage].Height, imageList[currImage].Width];
            blue = new double[imageList[currImage].Width, imageList[currImage].Height];
            zeros = new double[imageList[currImage].Height, imageList[currImage].Width];
            FourierOperations.SeparateColors(ref red, ref green, ref blue, imageList[currImage]);
            if (!channels.CheckedPics.Contains(1))
            {
                blue = zeros;
            }
            if (!channels.CheckedPics.Contains(2))
            {
                green = zeros;
            }
            if (!channels.CheckedPics.Contains(3))
            {
                red = zeros;
            }
            ((PictureBox)phTabContainer1.tempPanel.Controls[0]).Image = Operations.DisplayMatrix(FourierOperations.RecollectImage(red, green, blue, PostProcessing.None));

        }

        private void phTabContainer1_TabRemoved(object sender, EventArgs e)
        {
            int index = phTabContainer1.ActiveTabIndex;
            index = delImage;
            try
            {
                PicWindows.DropDownItems.RemoveByKey(imageList[delImage].Name);
                RemoveImageFromList(imageList[delImage].Id);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            DImage.DecreaseImagesCount();
            if (DImage.ImagesCount == 0)
            {
                phTabContainer2.tempPanel.Controls[0].Visible = false;
                phTabContainer3.tempPanel.Controls[0].Visible = false;
                this.DisableImageOperations();
            }
        }

        private void phTabContainer2_TabRemoved(object sender, EventArgs e)
        {
            switch (((PHTab)sender).Text)
            {
                case "History":
                    historyToolStripMenuItem.Checked = false;
                    break;
                case "Histogram":
                    histogramToolStripMenuItem.Checked = false;
                    break;
                case "Channels":
                    channelsToolStripMenuItem.Checked = false;
                    break;
                case "Image Info":
                    imageInfoToolStripMenuItem.Checked = false;
                    break;
            }
        }

        #region Properties
        /// <summary>
        /// Gets or sets a value indicating whether [selected index cahnge].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [selected index cahnge]; otherwise, <c>false</c>.
        /// </value>
        public static bool SelectedIndexChange
        {
            get { return selectedIndexChange; }
            set { selectedIndexChange = value; }
        }

        /// <summary>
        /// Gets or sets the e mode.
        /// </summary>
        /// <value>
        /// The e mode.
        /// </value>
        public static EditingMode EMode
        {
            get { return enumMode; }
            set { enumMode = value; }
        }

        /// <summary>
        /// Gets or sets the image list.
        /// </summary>
        /// <value>
        /// The image list.
        /// </value>
        public static List<DImage> ImageList
        {
            get { return imageList; }
            set { imageList = value; }
        }

        /// <summary>
        /// Gets or sets the illuminationoper.
        /// </summary>
        /// <value>
        /// The illuminationoper.
        /// </value>
        public static InputValuesEnum InputValueper
        {
            get { return inputValueoper; }
            set { inputValueoper = value; }
        }

        /// <summary>
        /// Gets or sets the curr image.
        /// </summary>
        /// <value>
        /// The curr image.
        /// </value>
        public static int CurrImage
        {
            get { return currImage; }
            set { currImage = value; }
        }

        /// <summary>
        /// Gets or sets the pic windows.
        /// </summary>
        /// <value>
        /// The pic windows.
        /// </value>
        public static ToolStripMenuItem PicWindows
        {
            get { return picWindows; }
            set { picWindows = value; }
        }

        /// <summary>
        /// Gets or sets the calc form objec.
        /// </summary>
        /// <value>
        /// The calc form objec.
        /// </value>
        public static CalculationForm CalcFormObjec
        {
            get { return calcFormObjec; }
            set { calcFormObjec = value; }
        }

        /// <summary>
        /// Gets or sets the name of the operation.
        /// </summary>
        /// <value>
        /// The name of the operation.
        /// </value>
        public static string OperationName
        {
            get { return operationName; }
            set { operationName = value; }
        }

        /// <summary>
        /// Gets the instance.
        /// </summary>
        public static Main Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Main();
                }

                return instance;
            }
        }

        /// <summary>
        /// Gets or sets the histo chart.
        /// </summary>
        /// <value>
        /// The histo chart.
        /// </value>
        public static HistogramChart HistoChart
        {
            get { return histoChart; }
            set { histoChart = value; }
        }

        /// <summary>
        /// Gets or sets the main tab container.
        /// </summary>
        /// <value>
        /// The main tab container.
        /// </value>
        public CustomControlTrial.PHTabContainer MainTabContainer
        {
            get { return this.phTabContainer1; }
            set { this.phTabContainer1 = value; }
        }

        /// <summary>
        /// Gets or sets the history list box.
        /// </summary>
        /// <value>
        /// The history list box.
        /// </value>
        public ListBox HistoryListBox
        {
            get { return this.historyListBox; }
            set { this.historyListBox = value; }
        }

        public PHPictureStringList PHPictureStringList1
        {
            get { return this.phPictureStringList1; }
            set { this.phPictureStringList1 = value; }
        }
        #endregion

        #region Methods
        /// <summary>
        /// Removes the image from list.
        /// </summary>
        /// <param name="id">The id.</param>
        public static void RemoveImageFromList(int id)
        {
            try
            {
                ImageList.RemoveAt(id);
                for (int i = id; i < ImageList.Count; i++)
                {
                    ImageList[i].Id--;
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        /// <summary>
        /// Shows the colors form.
        /// </summary>
        /// <returns>Returns colors</returns>
        public Color ShowColorsForm()
        {
            ColorDialog dialogColor = new ColorDialog();
            Color clr = new Color();
            if (dialogColor.ShowDialog() == DialogResult.OK)
            {
                clr = dialogColor.Color;
            }

            return clr;
        }

        /// <summary>
        /// Starts the histogram.
        /// </summary>
        private void StartHistogram()
        {
            this.HistogramTab.Panel.Controls.Clear();

            // phTabContainer2.tabs[0].TabSelected += new PHTab.TabSelectedHandler(Histgram_TabSelected);
            //this.phTabContainer2.tabs[0].Panel.Controls.Add(HistoChart.HistoChart);
            //this.phTabContainer2.tabs[0].Panel.Controls.Add(HistoChart.CheckRed);
            //this.phTabContainer2.tabs[0].Panel.Controls.Add(HistoChart.CheckGreen);
            //this.phTabContainer2.tabs[0].Panel.Controls.Add(HistoChart.CheckBlue);
            //this.phTabContainer2.tabs[0].Panel.Controls.Add(HistoChart.CheckGray);
            //this.phTabContainer2.tempPanel.AutoScroll = false;
            //this.phTabContainer2.UpdateViewPanel();
            //this.phTabContainer2.tempPanel.Controls[1].BringToFront();
            //this.phTabContainer2.tempPanel.Controls[2].BringToFront();
            //this.phTabContainer2.tempPanel.Controls[3].BringToFront();
            //this.phTabContainer2.tempPanel.Controls[4].BringToFront();
            //this.phTabContainer2.tempPanel.BackColor = Color.Black;
            this.HistogramPanel.Controls.Add(HistoChart.HistoChart);
            this.HistogramPanel.Controls.Add(HistoChart.CheckRed);
            this.HistogramPanel.Controls.Add(HistoChart.CheckGreen);
            this.HistogramPanel.Controls.Add(HistoChart.CheckBlue);
            this.HistogramPanel.Controls.Add(HistoChart.CheckGray);
            this.HistogramTab.Panel.Controls.Add(this.HistogramPanel);
            this.phTabContainer2.tempPanel.AutoScroll = false;
            this.HistogramPanel.Controls[1].BringToFront();
            this.HistogramPanel.Controls[2].BringToFront();
            this.HistogramPanel.Controls[3].BringToFront();
            this.HistogramPanel.Controls[4].BringToFront();
            this.HistogramPanel.Dock = DockStyle.Fill;
            this.phTabContainer2.UpdateViewPanel();
            this.phTabContainer2.tempPanel.Controls[0].BringToFront();
            this.HistogramPanel.BackColor = Color.Black;
            this.phTabContainer2.tempPanel.BackColor = Color.Black;

        }

        /// <summary>
        /// Handles the ActiveTabIndexChanged event of the phTabContainer1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PhTabContainer1_ActiveTabIndexChanged(object sender, EventArgs e)
        {
            delImage = currImage;
            currImage = this.phTabContainer1.ActiveTabIndex;
            HistoChart.Updatehisto(imageList[currImage]);
            UpdateChannelsPic();
            UpdateImageInfo();
            this.Lbl_Path.Text = imageList[currImage].FilePath;


            try
            {
                phTabContainer2.tempPanel.Controls[0].Visible = true;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            try
            {
                phTabContainer3.tempPanel.Controls[0].Visible = true;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }


            if (Main.currentInHistoryView != Main.CurrImage)
            {
                Main.Instance.PHPictureStringList1.RemoveFrom(-1);
                Main.currentInHistoryView = currImage;
                foreach (DImage item in Main.imageList[Main.currImage].ImHistory.HistoryList)
                {
                    CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
                    //phpicstring.Started = true;
                    phpicstring.Picture.Image = item.ImageBitmap;
                    phpicstring.Lbl_Text.Text = item.Name;
                    this.PHPictureStringList1.Checkable = false;
                    this.PHPictureStringList1.AddHistory(phpicstring);
                }
            }
            try
            {
                if (ImageList[CurrImage].IsVideo)
                {
                    HandleGUIEvents.CreateVedioToolStrip(ref this.VedioToolStrip);
                    VedioToolStrip.Invalidate();
                    VedioToolStrip.BringToFront();
                    this.Invalidate();
                    this.TKB_Vedio.Visible = true;
                }
                else
                {
                    this.VedioToolStrip.Visible = false;
                    this.TKB_Vedio.Visible = false;
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        /// <summary>
        /// Handles the ActiveTabIndexChanged event of the phTabContainer2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PhTabContainer2_ActiveTabIndexChanged(object sender, EventArgs e)
        {
            // this.StartHistogram();
        }

        /// <summary>
        /// Clears all buttons.
        /// </summary>
        private void ClearAllButtons()
        {
            this.SC_Rotate.BackColor = Color.Gray;
            this.SC_Crop.BackColor = Color.Gray;
            this.SC_Resize.BackColor = Color.Gray;
            this.SC_Shear.BackColor = Color.Gray;
            this.SC_Translate.BackColor = Color.Gray;
        }

        /// <summary>
        /// Validate resizing data.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The CancelEventArgs instance containing the event data.</param>
        private void PnlResize_Validating(object sender, CancelEventArgs e)
        {
            if (this.TxtboxTargetSize.Text == string.Empty)
            {
                MessageBox.Show("target resizing size is emty please set");
                return;
            }
            else
            {
                Regex targetSizeValidator;

                if (this.CmbMappingMethod.SelectedIndex == 0)
                {
                    targetSizeValidator = new Regex(@"\d");
                }
                else if (this.CmbMappingMethod.SelectedIndex == 1)
                {
                    targetSizeValidator = new Regex(@"\dX\d");
                }
                else
                {
                    MessageBox.Show("Select mapping method for resizing.");
                    return;
                }

                if (!targetSizeValidator.IsMatch(this.TxtboxTargetSize.Text))
                {
                    MessageBox.Show("Target size format is not valid either enter \"digit\" or \"digitXdigit\" ");
                    return;
                }
            }
        }
        #endregion

        #region Main form events
        /// <summary>
        /// Handles the Load event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void Main_Load(object sender, EventArgs e)
        {
            PicWindows = this.windowToolStripMenuItem;
            // MessageBox.Show("this location = " + this.Location);
            this.Location = new Point(0, 0);
            this.DisableImageOperations();
            fullScreenToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.Enter)));
            VideoTrackTimer.Start();
        }

        /// <summary>
        /// Handles the MouseClick event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void Main_MouseClick(object sender, MouseEventArgs e)
        {
            ImageList[Main.CurrImage].MyShaps.MouseClickAction(sender, e);
            Invalidate();
        }

        /// <summary>
        /// Handles the MouseDoubleClick event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void Main_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ImageList[Main.CurrImage].MyShaps.MouseDoubleClickAction(sender, e);
            Invalidate();
        }

        /// <summary>
        /// Handles the DragDrop event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
        private void Main_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] filePaths = (string[])e.Data.GetData(DataFormats.FileDrop);
                FileInfo[] files = new FileInfo[1];
                string searchPattern = "*.*";
                foreach (string fileLoc in filePaths)
                {
                    if (Directory.Exists(fileLoc))
                    {
                        DirectoryInfo di = new DirectoryInfo(fileLoc);
                        var directories = di.GetFiles("*", SearchOption.AllDirectories);
                        files = di.GetFiles(searchPattern, SearchOption.TopDirectoryOnly);
                    }
                    else
                    {
                        files[0] = new FileInfo(fileLoc);
                    }
                    // if (File.Exists(fileLoc))
                    {
                        foreach (FileInfo fi in files)
                        {
                            DImage image = new DImage(fi.FullName, ref enumMode);

                            if (image.Id == -1)
                            {
                                MessageBox.Show("Error Opening File " + fileLoc);
                            }
                            else
                            {
                                ImageList.Add(image);
                               // this.AddOwnedForm(ImageList[image.Id].Form1);
                                this.windowToolStripMenuItem.DropDownItems.Add(ImageList[image.Id].Name, ImageList[image.Id].ImageBitmap, delegate { phTabContainer1.tabs[image.Id].SetActive(); });
                                this.windowToolStripMenuItem.DropDownItems[2 + image.Id].Name = ImageList[image.Id].Name;
                                ImageList[image.Id].SetTab(this.phTabContainer1);
                            }
                        }
                    }

                }
                if (imageList.Count > 0)
                {
                    this.EnableImageOperations();
                }
                UpdateChannelsPic();
                UpdateImageInfo();
            }
        }

        /// <summary>
        /// Handles the Click event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Main_Click(object sender, EventArgs e)
        {
            EMode = EditingMode.Nothing;
            // PicForm.Mode1 = PicMode.Default;
            //  PicForm.Curso1 = CursorType.Default;

            // this.VerticalToolStrip.Visible = false;
            this.ClearAllButtons();
        }

        /// <summary>
        /// Handles the DragEnter event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DragEventArgs"/> instance containing the event data.</param>
        private void Main_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        /// <summary>
        /// Handles the Click event of the TSB_Close control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TSB_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the TSB_Minimize control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TSB_Minimize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        /// <summary>
        /// Handles the Click event of the BtnOpenImage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void BtnOpenImage_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Multiselect = true;
                if (openFile.ShowDialog() == DialogResult.OK)
                {
                    for (int i = 0; i < openFile.FileNames.Length; i++)
                    {
                        string[] fileType = openFile.FileNames[i].Split('.');
                        DImage image;

                        if (fileType[fileType.Length - 1] == "avi" || fileType[fileType.Length - 1] == "wmv")
                            image = new DImage(openFile.FileNames[i]);
                        else
                            image = new DImage(openFile.FileNames[i], ref enumMode);

                        if (image.Id == -1)
                        {
                            MessageBox.Show("Error Opening File " + openFile.SafeFileNames[i]);
                        }
                        else
                        {
                            ImageList.Add(image);
                            // this.AddOwnedForm(ImageList[image.Id].Form1);
                            this.windowToolStripMenuItem.DropDownItems.Add(ImageList[image.Id].Name, ImageList[image.Id].ImageBitmap, delegate { phTabContainer1.tabs[image.Id].SetActive(); });
                            this.windowToolStripMenuItem.DropDownItems[2 + image.Id].Name = ImageList[image.Id].Name;
                            ImageList[image.Id].SetTab(this.phTabContainer1);

                            // this.phTabContainer1.Add(image.Name);
                            // PictureBox b = new PictureBox();
                            // b.Image=image.ImageBitmap;
                            // b.Size = this.phTabContainer1.UpdatePanelSize();
                            // b.SizeMode = PictureBoxSizeMode.CenterImage;
                            // this.phTabContainer1.tabs[this.phTabContainer1.tabs.Count - 1].Panel.Controls.Add(b);
                            // this.phTabContainer1.UpdateViewPanel();
                        }
                    }
                    if (imageList.Count > 0)
                    {
                        this.EnableImageOperations();
                    }
                    UpdateChannelsPic();
                    UpdateImageInfo();
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        public void OpenImage(string path)
        {
            DImage image = new DImage(path, ref enumMode);

            if (image.Id == -1)
            {
                MessageBox.Show("Error Opening File " + path);
            }
            else
            {
                ImageList.Add(image);
              //  this.AddOwnedForm(ImageList[image.Id].Form1);
                this.windowToolStripMenuItem.DropDownItems.Add(ImageList[image.Id].Name, ImageList[image.Id].ImageBitmap, delegate { phTabContainer1.tabs[image.Id].SetActive(); });
                this.windowToolStripMenuItem.DropDownItems[2 + image.Id].Name = ImageList[image.Id].Name;
                ImageList[image.Id].SetTab(this.phTabContainer1);
            }
            if (imageList.Count > 0)
            {
                this.EnableImageOperations();
            }

            UpdateChannelsPic();
            UpdateImageInfo();
        }

        public DImage OpenImage(Bitmap bmp)
        {
            DImage image = new DImage(bmp);
            ImageList.Add(image);
            //this.AddOwnedForm(ImageList[image.Id].Form1);
            this.windowToolStripMenuItem.DropDownItems.Add(ImageList[image.Id].Name, ImageList[image.Id].ImageBitmap, delegate { phTabContainer1.tabs[image.Id].SetActive(); });
            this.windowToolStripMenuItem.DropDownItems[2 + image.Id].Name = ImageList[image.Id].Name;
            ImageList[image.Id].SetTab(this.phTabContainer1);

            if (imageList.Count > 0)
            {
                this.EnableImageOperations();
            }

            UpdateChannelsPic();
            UpdateImageInfo();

            return image;
        }

        public void CreateNewImage(int height, int width, Color clr, string name)
        {
            DImage image = new DImage(width, height, clr, name);
            ImageList.Add(image);
            this.windowToolStripMenuItem.DropDownItems.Add(ImageList[image.Id].Name, ImageList[image.Id].ImageBitmap, delegate { phTabContainer1.tabs[image.Id].SetActive(); });
            this.windowToolStripMenuItem.DropDownItems[2 + image.Id].Name = ImageList[image.Id].Name;
            ImageList[image.Id].SetTab(this.phTabContainer1);
            UpdateChannelsPic();
            UpdateImageInfo();
            this.EnableImageOperations();

        }

        /// <summary>
        /// Handles the Paint event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.PaintEventArgs"/> instance containing the event data.</param>
        private void Main_Paint(object sender, PaintEventArgs e)
        {
            // listBox1.DataSource = null;
            // if (Main.imageList.Count > 0)
            // {
            //    foreach (DImage item in Main.imageList[Main.currImage].ImHistory.HistoryList)
            //    {
            //        this.listBox1.Items.Add(item.Name);
            //    }
            // }
        }

        /// <summary>
        /// Handles the SizeChanged event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Main_SizeChanged(object sender, EventArgs e)
        {
            if (!this.isMinmize)
            {
                this.tableLayoutPanel1.ColumnStyles[0].SizeType = SizeType.AutoSize;
                this.tableLayoutPanel1.ColumnStyles[1].SizeType = SizeType.Percent;
                this.tableLayoutPanel1.ColumnStyles[2].SizeType = SizeType.AutoSize;

                this.tableLayoutPanel1.RowStyles[0].SizeType = SizeType.AutoSize;
                this.tableLayoutPanel1.RowStyles[1].SizeType = SizeType.AutoSize;
                this.tableLayoutPanel1.RowStyles[3].SizeType = SizeType.Percent;

                this.tableLayoutPanel2.RowStyles[0].SizeType = SizeType.AutoSize;
                this.tableLayoutPanel2.RowStyles[1].SizeType = SizeType.AutoSize;
                this.tableLayoutPanel2.RowStyles[2].SizeType = SizeType.AutoSize;

                this.tableLayoutPanel1.Size = this.Size;
                this.tableLayoutPanel2.Size = new Size(this.tableLayoutPanel2.Size.Width, this.Height);

                this.tableLayoutPanel1.SetColumn(this.pictureBox1, 0);
                phTabContainer1.Width = phTabContainer1.tempPanel.Width;
                PictureBox pcb;
                for (int i = 0; i < this.phTabContainer1.tabs.Count; i++)
                {
                    if (i == this.phTabContainer1.ActiveTabIndex)
                    {
                        pcb = (PictureBox)this.phTabContainer1.tempPanel.Controls[0];
                    }
                    else
                    {
                        pcb = (PictureBox)this.phTabContainer1.tabs[i].Panel.Controls[0];
                    }
                    pcb.Location = new Point((int)((this.phTabContainer1.tempPanel.Width - pcb.Width) * 0.5), (int)((this.phTabContainer1.tempPanel.Height - pcb.Height) * 0.5));
                    if (pcb.Location.X < 0 && pcb.Location.Y < 0)
                    {
                        pcb.Location = new Point(0, 0);
                    }
                    else if (pcb.Location.X < 0)
                    {
                        pcb.Location = new Point(0, pcb.Location.Y);
                    }
                    else if (pcb.Location.Y < 0)
                    {
                        pcb.Location = new Point(pcb.Location.X, 0);
                    }
                }
            }
        }

        /// <summary>
        /// Called when [border].
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="sickness">The sickness.</param>
        /// <returns>On border</returns>
        private int OnBorder(int x, int y, int sickness)
        {
            if (x > -sickness && x < sickness && y > -sickness && y < sickness)
            {
                return 5;
            }
            else if (x > -sickness && x < sickness && y > this.Height - sickness && y < this.Height + sickness)
            {
                return 7;
            }
            else if (y > -sickness && y < sickness && x > this.Width - sickness && x < this.Width + sickness)
            {
                return 6;
            }
            else if (y > this.Height - sickness && y < this.Height + sickness && x > this.Width - sickness && x < this.Width + sickness)
            {
                return 8;
            }
            else if (x > -sickness && x < sickness && y > -sickness && y < this.Size.Height + sickness)
            {
                return 1;
            }
            else if (x > this.Width - sickness && x < this.Width + sickness && y > -sickness && y < this.Size.Height + sickness)
            {
                return 2;
            }
            else if (y > -sickness && y < sickness && x > -sickness && x < this.Size.Width + sickness)
            {
                return 3;
            }
            else if (y > this.Height - sickness && y < this.Height + sickness && x > -sickness && x < this.Size.Width + sickness)
            {
                return 4;
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// Handles the MouseDown event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void Main_MouseDown(object sender, MouseEventArgs e)
        {
            // OnBorder(e.X, e.Y, 2);
            //  if (this.Cursor == System.Windows.Forms.Cursors.SizeNS || this.Cursor == System.Windows.Forms.Cursors.SizeWE)
            if (this.Cursor != System.Windows.Forms.Cursors.Default)
            {
                this.canResize = true;
            }
            else
            {
                this.canMove = true;
            }

            this.x = e.X;
            this.y = e.Y;
        }

        /// <summary>
        /// Handles the MouseUp event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void Main_MouseUp(object sender, MouseEventArgs e)
        {
            this.canResize = false;
            this.canMove = false;
            this.Cursor = System.Windows.Forms.Cursors.Default;
        }

        /// <summary>
        /// Handles the MouseMove event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void Main_MouseMove(object sender, MouseEventArgs e)
        {
            if (!this.canResize)
            {
                this.DrawResizeCursor(e);
            }

            if (this.canMove)
            {
                this.Location = new Point((int)this.Location.X + (int)(e.X - this.x), (int)this.Location.Y + (int)(e.Y - this.y));
            }
            else if (this.canResize)
            {
                this.ResizeForm(e);
            }
        }

        /// <summary>
        /// Draws the resize cursor.
        /// </summary>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void DrawResizeCursor(MouseEventArgs e)
        {
            if (!this.maxmized)
            {
                this.formBorder = this.OnBorder(e.X, e.Y, 3);
                if (this.formBorder > 0)
                {
                    if (this.formBorder == 1 || this.formBorder == 2)
                    {
                        this.Cursor = System.Windows.Forms.Cursors.SizeWE;
                    }
                    else if (this.formBorder == 3 || this.formBorder == 4)
                    {
                        this.Cursor = System.Windows.Forms.Cursors.SizeNS;
                    }
                    else if (/*this.Border == 5 ||*/ this.formBorder == 8)
                    {
                        this.Cursor = System.Windows.Forms.Cursors.SizeNWSE;
                    }
                    else if (this.formBorder == 6 || this.formBorder == 7)
                    {
                        // this.Cursor = System.Windows.Forms.Cursors.SizeNESW;
                    }
                }
                else
                {
                    // if (EMode == EditingMode.Nothing)
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                }
            }
            else
            {
                //if (EMode == EditingMode.Nothing)
                this.Cursor = System.Windows.Forms.Cursors.Default;
            }
        }

        /// <summary>
        /// Resizes the form.
        /// </summary>
        /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param>
        private void ResizeForm(MouseEventArgs e)
        {
            if (this.formBorder == 1)
            {
                if (this.Width < 800 && e.X - this.x > 0)
                {
                    return;
                }

                this.Location = new Point((int)this.Location.X + (int)(e.X - this.x), (int)this.Location.Y);
                this.Size -= new Size((int)(e.X - this.x), 0);
            }
            else if (this.formBorder == 3)
            {
                if (this.Height < 400 && e.Y - this.y > 0)
                {
                    return;
                }

                this.Location = new Point((int)this.Location.X, (int)this.Location.Y + (int)(e.Y - this.y));
                this.Size -= new Size(0, (int)(e.Y - this.y));
            }
            else if (this.formBorder == 2)
            {
                if (this.Width < 800 && e.X - this.x < 0)
                {
                    return;
                }

                this.Size += new Size((int)(e.X - this.x), 0);
                this.x = e.X;
            }
            else if (this.formBorder == 4)
            {
                if (this.Height < 400 && e.Y - this.y < 0)
                {
                    return;
                }

                this.Size += new Size(0, (int)(e.Y - this.y));
                this.y = e.Y;
            }
            else if (this.formBorder == 8)
            {
                if ((this.Height < 400 && e.Y - this.y < 0) || (this.Width < 800 && e.X - this.x < 0))
                {
                    return;
                }

                this.Size += new Size((int)(e.X - this.x), (int)(e.Y - this.y));
                this.y = e.Y;
                this.x = e.X;
            }

            // this.Width = this.Width < 400 ? 400 : this.Width;
            // this.Height = this.Height < 400 ? 400 : this.Height;
        }
        #endregion

        /// <summary>
        /// Handles the DrawItem event of the tabControl1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
        private void TabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            try
            {
                // This line of code will help you to 
                // change the apperance like size,name,style.
                Font f;

                // For background color
                Brush backBrush;

                // For forground color
                Brush foreBrush;

                // This construct will hell you to decide 
                // which tab page have current focus
                // to change the style.
                if (e.Index == this.TabCtrl_Pic.SelectedIndex)
                {
                    // This line of code will help you to 
                    // change the apperance like size,name,style.
                    f = new Font(e.Font, FontStyle.Bold | FontStyle.Bold);
                    f = new Font(e.Font, FontStyle.Bold);
                    backBrush = new System.Drawing.SolidBrush(Color.DarkGray);
                    foreBrush = Brushes.White;
                }
                else
                {
                    f = e.Font;
                    backBrush = new SolidBrush(e.BackColor);
                    foreBrush = new SolidBrush(e.ForeColor);
                }

                // To set the alignment of the caption.
                string tabName = this.TabCtrl_Pic.TabPages[e.Index].Text;
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;

                // Thsi will help you to fill the interior portion of
                // selected tabpage.
                e.Graphics.FillRectangle(backBrush, e.Bounds);
                System.Drawing.Rectangle r = e.Bounds;
                r = new System.Drawing.Rectangle(r.X, r.Y + 3, r.Width, r.Height - 3);
                e.Graphics.DrawString(tabName, f, foreBrush, r, sf);

                sf.Dispose();
                if (e.Index == this.TabCtrl_Pic.SelectedIndex)
                {
                    f.Dispose();
                    backBrush.Dispose();
                }
                else
                {
                    backBrush.Dispose();
                    foreBrush.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                MessageBox.Show(ex.Message.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            // Continue.........
        }

        #region Draw shapes
        /// <summary>
        /// Handles the Click event of the Btn_Resize control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_Resize_Click(object sender, EventArgs e)
        {
            inputValueoper = InputValuesEnum.Resizing;
            this.SetGrbInputValuesInvisible();

            this.lblGrbInputValues1.Visible = this.lblGrbInputValues2.Visible = this.lblGrbInputValues3.Visible = this.lblGrbTkb1.Visible = true;
            this.txtGrbInputValues2.Visible = this.txtGrbInputValues3.Visible = this.txtGrbInputValues1.Visible = true;
            this.cmbResizeAlgorithm.Visible = this.CmbInterpolationMode.Visible = this.TrkResize.Visible = true;

            this.grbInputValues.Visible = true;

            this.lblGrbInputValues1.Text = "Algorithm";
            this.lblGrbInputValues2.Text = "Height";
            this.lblGrbInputValues3.Text = "Width";
            this.lblGrbTkb1.Text = "Interpolation";

            this.ClearAllButtons();
            this.SC_Resize.BackColor = Color.LightGray;
            EMode = EditingMode.Resizing;
            //ImageProcessing.Forms.ResizeForm rf = Forms.ResizeForm.GetInstance();
            //rf.Show();
            //rf.BringToFront();
        }

        /// <summary>
        /// Handles the Click event of the btnPolygon control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnPolygon_Click(object sender, EventArgs e)
        {
            operationName = "Polygon drawn.";
            ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.POLYGON;
        }

        /// <summary>
        /// Handles the Click event of the btnCircle control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnCircle_Click(object sender, EventArgs e)
        {
            operationName = "Circle drawn.";
            ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.CIRCLE;
        }

        /// <summary>
        /// Handles the Click event of the btnRect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnRect_Click(object sender, EventArgs e)
        {
            operationName = "Rectangle drawn.";
            ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.RECTANGLE;
        }

        /// <summary>
        /// Handles the Click event of the btnEllipse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnEllipse_Click(object sender, EventArgs e)
        {
            operationName = "Ellipse drawn.";
            ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.ELLIPSE;
        }

        /// <summary>
        /// Handles the Click event of the btnScaleShape control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnScaleShape_Click(object sender, EventArgs e)
        {
            operationName = "Shape scaled.";
            // ImageList[Main.CurrImage].MyShaps.ScaleShapeAction(sender, e, this.txtScaleFactor.Text);
            Invalidate();
        }

        /// <summary>
        /// Handles the Click event of the btnFreeMove control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnFreeMove_Click(object sender, EventArgs e)
        {
            operationName = "Freehand shape drawn.";
            ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.FreeMove;
            this.Invalidate();
        }

        /// <summary>
        /// Handles the Click event of the btnGo control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnGo_Click(object sender, EventArgs e)
        {
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();
                    if (inputValueoper == InputValuesEnum.Resizing)
                    {
                        int factorY = 0, factorX = 0;
                        if (!int.TryParse(this.txtGrbInputValues2.Text, out factorY) || !int.TryParse(this.txtGrbInputValues3.Text, out factorX))
                        {
                            MessageBox.Show("Please enter correct integer width & height values");
                            return;
                        }

                        PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), factorX, factorY);
                    }
                    else
                    {
                        PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Width, ImageList[currImage].Height);
                    }

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        BtnGo_Single_Click(sender, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        if (inputValueoper == InputValuesEnum.Resizing)
                            ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    BtnGo_Single_Click(sender, e);
                }
            }
            else
            {
                BtnGo_Single_Click(sender, e);
            }
        }

        /// <summary>
        /// Handles the Click event of the BtnGo_Single control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnGo_Single_Click(object sender, EventArgs e)
        {
            string str;
            bool isNum;
            int localValue;
            switch (InputValueper)
            {
                case InputValuesEnum.Gamma:
                    str = this.txtGrbInputValues1.Text.Trim();
                    double gammaValue;
                    isNum = double.TryParse(str, out gammaValue);
                    if (isNum)
                    {
                        operationName = "Gamma corrected with value " + gammaValue.ToString();
                        ImageList[CurrImage].UpdateImage(PixelOperation.GammaCorrection(ImageList[Main.CurrImage].ImageStructArray, gammaValue));
                    }
                    else
                    {
                        errorProvider1.SetError(txtGrbInputValues1, "Invalide Value");
                    }

                    break;
                case InputValuesEnum.HistogramLocal:
                    str = this.txtGrbInputValues1.Text.Trim();
                    isNum = int.TryParse(str, out localValue);
                    if (isNum)
                    {
                        operationName = "Histogram equalized locally with value " + localValue.ToString();
                        Bitmap temp;
                        // ImageList[CurrImage].ImageBitmap = Equalization.HistogramLocalEqlization(ImageList[CurrImage].ImageBitmap,localValue);
                        // ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = Equalization.HistogramEqualization((Bitmap)((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image);
                         temp = Equalization.HistogramLocalEqlization(ImageList[CurrImage].ImageBitmap, localValue);
                        ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image =temp;
                        ImageList[CurrImage].UpdateImage(temp);
                    }
                    else
                    {
                        errorProvider1.SetError(txtGrbInputValues1, "Invalide Value");
                    }

                    break;
                case InputValuesEnum.MeanFilter2D:
                    str = this.txtGrbInputValues1.Text.Trim();
                    isNum = int.TryParse(str, out localValue);
                    if (isNum)
                    {
                        if (localValue % 2 != 0)
                        {
                            //this.errorProvider1.SetError(this.txtGrbInputValues1, string.Empty);
                            operationName = "Mean filter with mask: " + localValue.ToString();
                            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.MeanFilter2D(Main.imageList[Main.currImage], localValue));
                        }
                        else
                        {
                            //this.errorProvider1.SetError(this.txtGrbInputValues1, "Value Must be odd value");
                        }
                    }
                    else
                    {
                        //this.errorProvider1.SetError(this.txtGrbInputValues1, "Invalide Value");
                    }

                    break;

                case InputValuesEnum.MeanFilter1D:
                    str = this.txtGrbInputValues1.Text.Trim();
                    isNum = int.TryParse(str, out localValue);
                    if (isNum)
                    {
                        if (localValue % 2 != 0)
                        {
                            //this.errorProvider1.SetError(this.txtGrbInputValues1, string.Empty);
                            operationName = "Mean filter with mask: " + localValue.ToString();
                            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.Meanfilter1D(imageList[currImage].ImageBitmap, localValue));
                        }
                        else
                        {
                            //this.errorProvider1.SetError(this.txtGrbInputValues1, "Value Must be odd value");
                        }
                    }
                    else
                    {
                        //this.errorProvider1.SetError(this.txtGrbInputValues1, "Invalide Value");
                    }

                    break;
                case InputValuesEnum.GaussianFilter2D:
                    str = this.txtGrbInputValues1.Text.Trim();
                    double value;
                    isNum = double.TryParse(str, out value);
                    if (isNum)
                    {
                        operationName = "Gaussian filter with segma: " + value.ToString();
                        //this.errorProvider1.SetError(this.txtGrbInputValues1, string.Empty);
                        ImageList[CurrImage].UpdateImage(NeighborhoodOperations.GaussianFilter(Main.imageList[CurrImage], value));
                    }
                    else
                    {
                        this.errorProvider1.SetError(this.txtGrbInputValues1, "Invalide Value");
                    }

                    break;
                case InputValuesEnum.GaussianFilter1D:
                    str = this.txtGrbInputValues1.Text.Trim();
                    isNum = double.TryParse(str, out value);
                    if (isNum)
                    {
                        operationName = "Gaussian filter with sigma: " + value.ToString();
                        //this.errorProvider1.SetError(this.txtGrbInputValues1, string.Empty);
                        ImageList[CurrImage].UpdateImage(NeighborhoodOperations.GaussianFilter1D(imageList[CurrImage].ImageBitmap, value));
                    }
                    else
                    {
                        this.errorProvider1.SetError(this.txtGrbInputValues1, "Invalid Value");
                    }

                    break;

                case InputValuesEnum.SaltAndPepperNoise:
                    float saltProb = 0, pepperProb = 0;
                    if (!(float.TryParse(this.txtGrbInputValues1.Text, out saltProb) && float.TryParse(this.txtGrbInputValues2.Text, out pepperProb)))
                    {
                        MessageBox.Show("Please enter correct decimal values");
                        return;
                    }

                    if (saltProb + pepperProb != 1)
                    {
                        MessageBox.Show("Invalid input, probabilities have to be equal to 0");
                        return;
                    }

                    operationName = "Salt %" + (saltProb * 100).ToString() + " and Pepper %" + (pepperProb * 100).ToString();
                    imageList[currImage].UpdateImage(Noise.AddSaltAndPepper(imageList[currImage].ImageBitmap, saltProb, pepperProb, this.TkbGrbInputValues1.Value));
                    // ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = Noise.AddSalt_PepperFast((Bitmap)((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image, saltProb, pepperProb, this.TkbGrbInputValues1.Value);

                    break;

                case InputValuesEnum.GaussianNoise:
                    double sigma = 0, miu = 0;
                    if (!(double.TryParse(this.txtGrbInputValues1.Text, out sigma) && double.TryParse(this.txtGrbInputValues2.Text, out miu)))
                    {
                        MessageBox.Show("Please enter correct decimal values");
                        return;
                    }

                    operationName = "Gaussian noise with sigma: " + sigma.ToString() + " and miu: " + miu.ToString();
                    ((PictureBox)Main.Instance.MainTabContainer.tempPanel.Controls[0]).Image = Noise.AddGaussianNoiseBitmab(imageList[currImage].ImageBitmap, sigma, miu, this.TkbGrbInputValues1.Value);
                    // imageList[currImage].UpdateImage(Noise.AddGaussianNoise(imageList[currImage].ImageStructArray, sigma, miu, this.TkbGrbInputValues1.Value));
                    break;

                case InputValuesEnum.UniformNoise:
                    int a = 0, b = 0;
                    if (!(int.TryParse(this.txtGrbInputValues1.Text, out a) && int.TryParse(this.txtGrbInputValues2.Text, out b)))
                    {
                        MessageBox.Show("Please enter correct decimal values");
                        return;
                    }

                    operationName = "Uniform noise with a: " + a.ToString() + " and b: " + b.ToString();
                    imageList[currImage].UpdateImage(Noise.AddUniformNoise(imageList[currImage].ImageStructArray, a, b, this.TkbGrbInputValues1.Value));
                    break;

                case InputValuesEnum.RaleighNoise:
                    double aval = 0, bval = 0;
                    if (!(double.TryParse(this.txtGrbInputValues1.Text, out aval) && double.TryParse(this.txtGrbInputValues2.Text, out bval)))
                    {
                        MessageBox.Show("Please enter correct decimal values");
                        return;
                    }

                    operationName = "Raleigh noise with aval: " + aval.ToString() + " and bval: " + bval.ToString();
                    imageList[currImage].UpdateImage(Noise.AddRaleighNoise(imageList[currImage].ImageStructArray, aval, bval, this.TkbGrbInputValues1.Value));
                    break;

                case InputValuesEnum.GammaNoise:
                    double avalue = 0, bvallue = 0;
                    if (!(double.TryParse(this.txtGrbInputValues1.Text, out aval) && double.TryParse(this.txtGrbInputValues2.Text, out bval)))
                    {
                        MessageBox.Show("Please enter correct decimal values");
                        return;
                    }

                    operationName = "Gamma noise with aValue: " + avalue.ToString() + " and bValue: " + bvallue.ToString();
                    imageList[currImage].UpdateImage(Noise.AddGammaNoise(imageList[currImage].ImageStructArray, avalue, bvallue, this.TkbGrbInputValues1.Value));
                    break;

                case InputValuesEnum.ExponentialNoise:
                    double ampValue = 0;
                    if (!double.TryParse(this.txtGrbInputValues1.Text, out ampValue))
                    {
                        MessageBox.Show("Please enter correct decimal values");
                        return;
                    }

                    operationName = "Exponential noise with aValue: " + ampValue.ToString();
                    imageList[currImage].UpdateImage(Noise.AddExponentialNoise(imageList[currImage].ImageStructArray, ampValue, this.TkbGrbInputValues1.Value));
                    break;

                case InputValuesEnum.NoiseFilter:
                    int masksize = 0;
                    if (!int.TryParse(this.txtGrbInputValues1.Text, out masksize))
                    {
                        MessageBox.Show("Please enter correct integer value");
                        return;
                    }

                    Noise noise = new Noise();
                    operationName = "Noise filtered with mask size: " + masksize.ToString();
                    //((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = noise.LinearConvolution((Bitmap)((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image, masksize, filterType, AddingType.Black, PostProcessing.None);
                    imageList[currImage].UpdateImage(noise.LinearConvolution(imageList[currImage].ImageBitmap, masksize, filterType, AddingType.Black, PostProcessing.None));
                    break;
                case InputValuesEnum.Quantization:
                    if (!double.TryParse(this.txtGrbInputValues1.Text, out value))
                    {
                        MessageBox.Show("Please input correct value");
                        return;
                    }

                    Bitmap bmp = (Bitmap)((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image;
                    BitmapData bmpd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    int extraBytes = bmpd.Stride - bmp.Width * 3;
                    PHFastCpp.PHQuantization((int)bmpd.Scan0, bmp.Width, bmp.Height, extraBytes, value);
                    bmp.UnlockBits(bmpd);
                    operationName = "Quantization value: " + value.ToString();
                    imageList[CurrImage].UpdateImage(bmp);
                    break;

                case InputValuesEnum.Resizing:
                    int factorY = 0, factorX = 0;
                    if (!int.TryParse(this.txtGrbInputValues2.Text, out factorY) || !int.TryParse(this.txtGrbInputValues3.Text, out factorX))
                    {
                        MessageBox.Show("Please enter correct integer width & height values");
                        return;
                    }


                    switch (this.cmbResizeAlgorithm.SelectedIndex)
                    {
                        // 0-order (by repeating pixels) //direct mapping by factor
                        case 0:
                            Main.OperationName = "Resize nearest neighbor to: " + factorX + " X " + factorY;
                            Main.ImageList[Main.CurrImage].UpdateImage(ResizeImage.NearestNeighborResize(Main.ImageList[Main.CurrImage].ImageBitmap, false, factorX, factorY));
                            break;

                        // Bilinear
                        case 1:
                            Main.OperationName = "Resize Billinear to: " + factorX + " X " + factorY;
                            //((PictureBox)Main.Instance.MainTabContainer.tempPanel.Controls[0]).Image = ResizeImage.BiLineResize(factorX, factorY, Main.ImageList[Main.CurrImage].ImageBitmap);
                            Main.ImageList[Main.CurrImage].UpdateImage(ResizeImage.BiLineResize(factorX, factorY, Main.ImageList[Main.CurrImage].ImageBitmap));
                            break;

                        // Bi-cubic
                        case 2:
                            Main.OperationName = "Resize Bicubic to: " + factorX + " X " + factorY;
                            Main.ImageList[Main.CurrImage].UpdateImage(ResizeImage.BicubicResize(factorX, factorY, Main.ImageList[Main.CurrImage].ImageBitmap, this.CmbInterpolationMode.SelectedIndex));
                            break;
                    }
                    break;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSelect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnSelect_Click(object sender, EventArgs e)
        {
            ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.NONE;
        }
        #endregion

        #region Toolbox items clicks
        /// <summary>
        /// Handles the ItemClicked event of the ToolBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.ToolStripItemClickedEventArgs"/> instance containing the event data.</param>
        private void ToolBox_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            return;
        }
        #endregion

        #region Pixel Operations
        /// <summary>
        /// Handles the Click event of the gammaCorrectionToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void GammaCorrectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputValueper = InputValuesEnum.Gamma;
            this.grbInputValues.Visible = true;
            this.txtGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Gamma Value";
            this.lblGrbInputValues1.Visible = true;
            operationName = "Gamma corrected";
        }

        /// <summary>
        /// Handles the Click event of the illToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void IllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            return;
        }

        /// <summary>
        /// Handles the Click event of the byNameToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ByNameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<ToolStripItem> toollist = new List<ToolStripItem>();

            for (int i = 2; i < PicWindows.DropDownItems.Count; i++)
            {
                toollist.Add(PicWindows.DropDownItems[i]);
                PicWindows.DropDownItems.Remove(PicWindows.DropDownItems[i]);
            }

            toollist.Sort();
            foreach (ToolStripItem item in toollist)
            {
                PicWindows.DropDownItems.Add(item);
            }
        }

        /// <summary>
        /// Handles the Click event of the calculationToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void CalculationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CalcFormObjec = new CalculationForm();
            imageList[currImage].Form1.AddOwnedForm(calcFormObjec);
            CalcFormObjec.Show();
        }

        /// <summary>
        /// Handles the Click event of the brightnessAndContrastToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HistogramToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Open an image first please.");
                return;
            }
            if (phTabContainer2.tabs.Count != 0)
            {
                HistogramChart histo = new HistogramChart(ImageList[CurrImage]);
                //imageList[currImage].Form1.AddOwnedForm(histo);
                histo.Show();
            }
            else if (phTabContainer2.tabs.Count == 0)
            {
                phTabContainer2.Add("Histogram");
                phTabContainer2.ResetTabs();
                HistogramTab = phTabContainer2.tabs[0];
                this.StartHistogram();
            }
            ((ToolStripMenuItem)sender).Checked = true;
        }

        /// <summary>
        /// Handles the Click event of the brightnessAndContrastToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BrightnessAndContrastToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Open an image first please.");
                return;
            }

            operationName = "Brightness/Contrast";
            BrightnessAndContrast form = new BrightnessAndContrast(ImageList[CurrImage]);
            //imageList[currImage].Form1.AddOwnedForm(form);
            form.Show();
        }

        /// <summary>
        /// Handles the Click event of the notToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void NotToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "NOT operation";
            imageList[currImage].UpdateImage(PixelOperation.NotOperation(imageList[Main.currImage].ImageStructArray));
            return;
        }

        /// <summary>
        /// Handles the Click event of the quantizationToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void QuantizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Quantization";
            Quantization quant = new Quantization(ImageList[CurrImage]);
            imageList[currImage].Form1.AddOwnedForm(quant);
            quant.Show();
        }

        /// <summary>
        /// Handles the Click event of the histogramEqualizationToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HistogramEqualizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Histogram equalization";
            Bitmap temp;
            temp = Equalization.HistogramEqualization(ImageList[CurrImage].ImageBitmap);
            imageList[currImage].UpdateImage(Operations.ConvertBitmapToStructure(temp));

        }

        /// <summary>
        /// Handles the Click event of the spyMessagingToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SpyMessagingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            SpyMessaging sm = new SpyMessaging(ImageList[CurrImage]);
            imageList[currImage].Form1.AddOwnedForm(sm);

            sm.Show();
        }

        /// <summary>
        /// Handles the Click event of the exitToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the changeColorToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ChangeColorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // ImageList[Main.CurrImage].MyShaps.ChangeColorToolStripMenuItemAction(sender, e, this.colorDialog1);
            // Invalidate();
            Color c = this.ShowColorsForm();
            Color lightC;
            lightC = Color.FromArgb((int)NeighborhoodOperations.CutOff(c.R + 20, 0, 255), (int)NeighborhoodOperations.CutOff(c.G + 20, 0, 255), (int)NeighborhoodOperations.CutOff(c.B + 20, 0, 255));
            this.tableLayoutPanel1.BackColor = c;
            this.BackColor = c;
            this.MainMenuStrip.BackColor = c;
            this.phTabContainer1.tempPanel.BackColor = c;
            //this.phTabContainer2.tempPanel.BackColor = c;
            this.phTabContainer3.tempPanel.BackColor = c;
            this.phTabContainer1.BackColor = lightC;
            this.phTabContainer2.BackColor = lightC;
            this.phTabContainer3.BackColor = lightC;
            this.historyListBox.BackColor = c;
            // this.phTabContainer3.BackColor = lightC;
            if (c == Color.Black)
            {
                this.MainMenuStrip.ForeColor = Color.White;
            }
            else
            {
                this.MainMenuStrip.ForeColor = Color.Black;
            }

            // this.MainMenuStrip.ForeColor = Color.FromArgb(255 - c.R, 255 - c.G, 255 - c.B);
            // this.statusStrip1.BackColor = c;
            // ImageStructure[,] mask = Operations.GetImageOfColor(c, Pcb_Close.Image.Height, Pcb_Close.Image.Width);
            // this.Pcb_Close.Image = Operations.DisplayMatrixAlpha(CalcOperation.AddColor2image(Operations.ConvertBitmapToStructure((Bitmap)this.Pcb_Close.Image), c, 0.9));
            // PictureBox p = (PictureBox)this.HistogramTab.tabPic;
            // p.Image = Operations.DisplayMatrix(CalcOperation.AddColor2image(Operations.ConvertBitmapToStructure((Bitmap)p.Image), c, 0.9));
        }

        /// <summary>
        /// Handles the Click event of the histogramMatchingToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HistogramMatchingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Histogram matching";
            HistogramsMatchingForm matchForm = new HistogramsMatchingForm();
            matchForm.Show();
        }

        /// <summary>
        /// Handles the Click event of the pixelOperationsGraphToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PixelOperationsGraphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PixelOperationsGraph pog = new PixelOperationsGraph(imageList[currImage]);
            imageList[currImage].Form1.AddOwnedForm(pog);
            pog.Show();
        }

        /// <summary>
        /// Handles the Click event of the histogramLocalEqlizationToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HistogramLocalEqlizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            InputValueper = InputValuesEnum.HistogramLocal;
            this.grbInputValues.Visible = true;
            this.txtGrbInputValues1.Visible = this.lblGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Mask Value";
            this.grbInputValues.Text = "Histogram local equalization";
            operationName = "Histogram local equalization";

        }
        #endregion

        #region Sharpening/Smoothing
        /// <summary>
        /// Handles the Click event of the GreyscaleToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void GreyscaleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Image greyscaled";
            ImageList[CurrImage].UpdateImage(Operations.GreyScale(ImageList[CurrImage].ImageStructArray));
            ImageList[CurrImage].GreyScale = true;
        }

        /// <summary>
        /// Handles the Click event of the sarpingToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SarpingToolStripMenuItem_Click(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Handles the Click event of the verticalToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void VerticalToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            operationName = "Image sharpened on vertical black";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.ShearpingVerticalBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the diagonalLeftToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DiagonalLeftToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Image sharpened on left diagonal black";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.ShearpingLeftDiagonalBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the horizontalToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HorizontalToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            operationName = "Image sharpened horizontally";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.ShearpingHorizontalBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the diagonalRigthToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void DiagonalRigthToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Image sharpened on right diagonal";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.ShearpingRigthDiagonalBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the laplacianToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void LaplacianToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Laplacian black edge detection";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionLaplacianBlack(ImageList[currImage]));
        }
        #endregion

        /// <summary>
        /// Handles the Click event of the customConvolutionToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void CustomConvolutionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConvolutionForm newForm = new ConvolutionForm();
            newForm.Show();
        }

        #region Border Operations
        /// <summary>
        /// Handles the Click event of the blackBorderToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BlackBorderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionHorizontalBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the sameBorderToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SameBorderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionHorizontalSame(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the blackBorderToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BlackBorderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionVerticalBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the sameBorderToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SameBorderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionVerticalSame(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the blackBorderToolStripMenuItem2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BlackBorderToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionDiagonalLeftBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the sameBorderToolStripMenuItem2 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SameBorderToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionDiagonalLeftSame(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the blackBorderToolStripMenuItem3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BlackBorderToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionDiagonalRigthBlack(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the sameBorderToolStripMenuItem3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SameBorderToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.EdgeDetictionDiagonalRigthSame(ImageList[currImage]));
        }
        #endregion

        /// <summary>
        /// Handles the Click event of the ToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            InputValueper = InputValuesEnum.MeanFilter2D;
            this.grbInputValues.Visible = true;
            this.txtGrbInputValues1.Visible = this.lblGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Mask Value";
            this.grbInputValues.Text = "Mean filter 2D";
        }

        /// <summary>
        /// Handles the Click event of the ToolStripMenuItem3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            operationName = "Gaussian filter with sigma: ";
            InputValueper = InputValuesEnum.GaussianFilter2D;
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Gaussian filter";
            this.txtGrbInputValues1.Visible = this.lblGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Segma value";
        }

        /// <summary>
        /// Handles the Click event of the cannyFilterToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void CannyFilterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Forms.CnnyForm newform = new Forms.CnnyForm(Main.imageList[currImage].ImageBitmap);
            newform.Show();
        }

        /// <summary>
        /// Handles the Click event of the laToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void LaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Laplacian sharpening";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.ShearpingLaplacianSame(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the verticalToolStripMenuItem3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void VerticalToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            operationName = "Soble done on Y-Axis.";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.SobleY(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the horizontalToolStripMenuItem3 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HorizontalToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            operationName = "Soble done on X-Axis.";
            ImageList[CurrImage].UpdateImage(NeighborhoodOperations.SobleX(ImageList[currImage]));
        }

        /// <summary>
        /// Handles the Click event of the effectsToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void EffectsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Effects effxctsform = new Effects();
            effxctsform.Show();
        }

        /// <summary>
        /// Handles the Click event of the BtnZoom control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnZoom_Click(object sender, EventArgs e)
        {
            ZoomForm zf = new ZoomForm();
            zf.Show();

            // operationName = "Picture zoomed.";
        }

        /// <summary>
        /// BTNs the hide salt and pepper.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnInputValues(object sender, EventArgs e)
        {
            this.grbInputValues.Visible = false;
        }

        /// <summary>
        /// Handles the Click event of the metaDataBarToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MetaDataBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Main.imageList[Main.currImage].
            return;
        }

        #region ThreShold
        /// <summary>
        /// Handles the Click event of the toBlackToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ToBlackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ThreSholdBlackWhite form = new ThreSholdBlackWhite("black");
            form.Show();
        }

        #endregion

        #region Fourier
        /// <summary>
        /// Handles the Click event of the FourierEffectsToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FourierEffectsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            FourierImage fi = new FourierImage(ImageList[currImage]);
            fi.Init();
            FourierEffectsForm fourier = new FourierEffectsForm(fi);
            fourier.Show();
        }

        /// <summary>
        /// Handles the Click event of the FourierTranslationToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FourierTranslationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            FrequencyDomain freqDomain = new FrequencyDomain(imageList[currImage]);
            freqDomain.Show();
        }

        /// <summary>
        /// Handles the Click event of the retinexToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void RetinexToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int[] sigma = new int[] { 15, 80, 250 };
            // Retinx retObj = new Retinx();

            // MWNumericArray temp=retObj.GetRtinx(
            //   double[,] res=(double[,])temp.ToArray(MWArrayComponent.Real);
        }
        #endregion

        #region Noise
        /// <summary>
        /// Handles the Click event of the periodicNoiseToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PeriodicNoiseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.groupBoxPeriodicNoise.Visible = true;

            // test only
            operationName = "Periodic noise added.";
          //  Main.imageList[Main.currImage].UpdateImage(Noise.AddPeriodicNoise(Main.imageList[Main.currImage].ImageStructArray, 200, 30, 0, 40, 0));
        }

        /// <summary>
        /// Handles the Click event of the GaussianNoiseToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void GaussianNoiseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            operationName = "Gaussian noise with sigma: ";
            this.grbInputValues.Visible = true;
            inputValueoper = InputValuesEnum.GaussianNoise;
            this.grbInputValues.Text = "Gaussian noise";

            this.lblGrbInputValues1.Visible = this.lblGrbInputValues2.Visible = this.txtGrbInputValues1.Visible = this.txtGrbInputValues2.Visible = true;
            this.TkbGrbInputValues1.Visible = this.lblGrbTkb1.Visible = this.TxtGrbInputValuesTkb1.Visible = true;
            this.lblGrbInputValues1.Text = "Sigma";
            this.lblGrbInputValues2.Text = "Miu";
        }

        /// <summary>
        /// Handles the Click event of the UniformToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void UniformToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();

            operationName = "Uniform noise added.";
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Uniform noise";
            inputValueoper = InputValuesEnum.UniformNoise;

            this.lblGrbInputValues1.Visible = this.lblGrbInputValues2.Visible = this.txtGrbInputValues1.Visible = this.txtGrbInputValues2.Visible = true;
            this.TkbGrbInputValues1.Visible = this.TxtGrbInputValuesTkb1.Visible = this.lblGrbTkb1.Visible = true;
            this.lblGrbInputValues1.Text = "a";
            this.lblGrbInputValues2.Text = "b";
        }

        /// <summary>
        /// Handles the Click event of the minToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MinToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            SetGrbInputValuesInvisible();
            if (item != null)
            {
                switch (item.Text)
                {
                    case "Min 2D":
                        filterType = FilterType.Min2D;
                        this.grbInputValues.Text = "Min 2D filter";
                        operationName = "Min Filter ";
                        break;
                    case "Min 1D":
                        filterType = FilterType.Min1D;
                        this.grbInputValues.Text = "Min 1D filter";
                        operationName = "Min Filter ";
                        break;
                    case "Max 2D":
                        filterType = FilterType.Max2D;
                        this.grbInputValues.Text = "Max 2D filter";
                        operationName = "Max Filter ";
                        break;
                    case "Max 1D":
                        filterType = FilterType.Max1D;
                        this.grbInputValues.Text = "Max 1D filter";
                        operationName = "Max Filter ";
                        break;
                    case "Mid Point":
                        filterType = FilterType.MidPoint;
                        this.grbInputValues.Text = "Mid point filter";
                        operationName = "Mid point Filter ";
                        break;
                    case "Median":
                        filterType = FilterType.Median;
                        this.grbInputValues.Text = "Median filter";
                        operationName = "Median Filter ";
                        break;
                    case "Arithmetic Mean":
                        filterType = FilterType.AriMean;
                        this.grbInputValues.Text = "Arithmetic mean filter";
                        operationName = "Arithmetic mean Filter ";
                        break;
                    case "Geometric Mean":
                        filterType = FilterType.GeoMean;
                        this.grbInputValues.Text = "Geometric mean filter";
                        operationName = "Geometric mean Filter ";
                        break;
                    case "Adaptive Median":
                        filterType = FilterType.AdaptiveMean;
                        this.grbInputValues.Text = "Adaptive median filter";
                        operationName = "Adaptive median filter";
                        break;
                    default:
                        break;
                }
            }

            inputValueoper = InputValuesEnum.NoiseFilter;
            this.grbInputValues.Visible = true;
            this.lblGrbInputValues1.Visible = this.txtGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Mask size";
            operationName += "done";
        }

        /// <summary>
        /// Handles the Scroll event of the TkbNoisePercentage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TkbNoisePercentage_Scroll(object sender, EventArgs e)
        {
            this.TxtGrbInputValuesTkb1.Text = this.TkbGrbInputValues1.Value.ToString();
        }

        /// <summary>
        /// Handles the Click event of the SaltAndPepperToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SaltAndPepperToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Salt and pepper noise added";
            this.grbInputValues.Visible = true;
            inputValueoper = InputValuesEnum.SaltAndPepperNoise;
            this.grbInputValues.Text = "Salt and pepper noise";

            this.lblGrbInputValues1.Visible = this.lblGrbInputValues2.Visible = this.txtGrbInputValues1.Visible = this.txtGrbInputValues2.Visible = true;
            this.lblGrbTkb1.Visible = this.TkbGrbInputValues1.Visible = this.TxtGrbInputValuesTkb1.Visible = true;
            this.lblGrbInputValues1.Text = "Salt probability";
            this.lblGrbInputValues2.Text = "Pepper probability";
        }

        /// <summary>
        /// Handles the Click event of the exponentialToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ExponentialToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Exponential noise added";
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Exponential noise";
            inputValueoper = InputValuesEnum.ExponentialNoise;

            this.lblGrbInputValues1.Visible = this.txtGrbInputValues1.Visible = true;
            this.TkbGrbInputValues1.Visible = this.TxtGrbInputValuesTkb1.Visible = this.lblGrbTkb1.Visible = true;
            this.lblGrbInputValues1.Text = "a";
        }

        /// <summary>
        /// Handles the Click event of the gammaToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void GammaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Gamma noise added";
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Gamma noise";
            inputValueoper = InputValuesEnum.GammaNoise;

            this.lblGrbInputValues1.Visible = this.lblGrbInputValues2.Visible = this.txtGrbInputValues1.Visible = this.txtGrbInputValues2.Visible = true;
            this.TkbGrbInputValues1.Visible = this.TxtGrbInputValuesTkb1.Visible = this.lblGrbTkb1.Visible = true;
            this.lblGrbInputValues1.Text = "a";
            this.lblGrbInputValues2.Text = "b";
        }

        /// <summary>
        /// Handles the Click event of the raleighToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void RaleighToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Raleigh noise added";
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Raleigh noise";
            inputValueoper = InputValuesEnum.RaleighNoise;

            this.lblGrbInputValues1.Visible = this.lblGrbInputValues2.Visible = this.txtGrbInputValues1.Visible = this.txtGrbInputValues2.Visible = true;
            this.TkbGrbInputValues1.Visible = this.TxtGrbInputValuesTkb1.Visible = this.lblGrbTkb1.Visible = true;
            this.lblGrbInputValues1.Text = "a";
            this.lblGrbInputValues2.Text = "b";
        }
        #endregion

        #region Transformation
        /// <summary>
        /// Handles the Click event of the SC_Rotate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SC_Rotate_Click(object sender, EventArgs e)
        {
            operationName = "Image rotated";

            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Rotate.BackColor = Color.LightGray;
            EMode = EditingMode.Rotating;
            HandleGUIEvents.CreateRotateToolStrip(ref this.VerticalToolStrip);
        }

        /// <summary>
        /// Handles the Click event of the SC_Resize control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SC_Resize_Click(object sender, EventArgs e)
        {
            operationName = "Image resized";

            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Resize.BackColor = Color.LightGray;
            EMode = EditingMode.Resizing;
        }

        /// <summary>
        /// Handles the Click event of the SC_Translate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SC_Translate_Click(object sender, EventArgs e)
        {
            operationName = "Image translated";

            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Translate.BackColor = Color.LightGray;
            EMode = EditingMode.Translating;
            HandleGUIEvents.CreateTranslateToolStrip(ref this.VerticalToolStrip);
        }

        /// <summary>
        /// Handles the Click event of the SC_Shear control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SC_Shear_Click(object sender, EventArgs e)
        {
            operationName = "Image sheared";
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Shear.BackColor = Color.LightGray;
            EMode = EditingMode.Shearing;
            HandleGUIEvents.CreateShearToolStrip(ref this.VerticalToolStrip);
        }

        /// <summary>
        /// Handles the user request for resizing the opended image.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void BtnResize_Click(object sender, EventArgs e)
        {
            // this.Validate();
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            bool directMapping = false;
            int factorX = 1;
            int factorY = 1;
            try
            {
                if (this.CmbMappingMethod.SelectedIndex == 0)
                {
                    directMapping = true;
                    factorX = factorY = int.Parse(this.TxtboxTargetSize.Text);
                }
                else if (this.CmbMappingMethod.SelectedIndex == 1)
                {
                    directMapping = false;
                    string[] targetSize = this.TxtboxTargetSize.Text.Split('X');
                    factorX = int.Parse(targetSize[0]);
                    factorY = int.Parse(targetSize[1]);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                MessageBox.Show("Refill the target size correctly.\n" + ex.ToString());
                ////throw;
            }

            int resizeAlgo = this.CmbResizingAlgo.SelectedIndex;
            switch (resizeAlgo)
            {
                // 0-order (by repeating pixels) //direct mapping by factor
                case 0:
                    //ImageList[CurrImage].UpdateImage(ResizeImage.NearestNeighborResize(ImageList[CurrImage].ImageStructArray, directMapping, factorX, factorY));
                    break;

                // Bilinear
                case 1:
                    //ImageList[CurrImage].UpdateImage(ResizeImage.BiLineResize(factorX, factorY, ImageList[CurrImage].ImageStructArray));
                    break;

                // Bi-cubic
                case 2:
                    ImageList[CurrImage].UpdateImage(ResizeImage.BicubicResize(factorX, factorY, ImageList[CurrImage].ImageStructArray, 0));
                    break;

                // S-Spline
                case 3:
                    break;
            }

            operationName = "Image Resized";
        }

        /// <summary>
        /// Handles the Click event of the Btn_Crop control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_Crop_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            imageList[currImage].BackupImageArray();
            EMode = EditingMode.Cropping;
            HandleGUIEvents.CreateCropToolStrip(ref this.VerticalToolStrip);
            VerticalToolStrip.Invalidate();
            VerticalToolStrip.BringToFront();
            this.Invalidate();

            operationName = "Image cropped";
        }

        /// <summary>
        /// Handles the Click event of the Btn_Translate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_Translate_Click(object sender, EventArgs e)
        {
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Width, ImageList[currImage].Height);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        Btn_Translate_Single_Click(sender, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    Btn_Translate_Single_Click(sender, e);
                }
            }
            else
            {
                Btn_Translate_Single_Click(sender, e);
            }
        }

        private void Btn_Translate_Single_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

        again:
            this.ClearAllButtons();
            this.SC_Translate.BackColor = Color.LightGray;
            EMode = EditingMode.Translating;
            string translate = Interaction.InputBox("Please Enger The angle of Shearing", "Translating", "0X0");
            try
            {
                if (translate != string.Empty)
                {
                    if (translate.Contains('x') || translate.Contains('X'))
                    {
                        string[] offset = translate.Split(new char[] { 'x', 'X' });
                        operationName = "Image translated";
                        ImageList[CurrImage].UpdateImage(Transformation.Translate(ImageList[CurrImage].ImageStructArray, int.Parse(offset[0]), int.Parse(offset[1])));
                    }
                    else
                    {
                        MessageBox.Show("please enter in format number X number");
                        goto again;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            // operationName = "Image translated";
        }

        /// <summary>
        /// Handles the Click event of the Btn_Rotate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_Rotate_Click(object sender, EventArgs e)
        {
            double doubleAngle = 0;
            string angle = Interaction.InputBox("Please Enter The angle of Rotation", "Rotation", "0");
            if (angle != string.Empty)
            {
                operationName = "Image rotated with an angle " + angle.ToString();
                if (!double.TryParse(angle, out doubleAngle))
                {
                    MessageBox.Show("Please enter a correct angle value.");
                    return;
                }
            }

            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    int newWidth = 0, newHeight = 0;
                    Transformation.CalculateRotateNewSize(doubleAngle, ImageList[currImage].Width, ImageList[currImage].Height, ref newWidth, ref newHeight);

                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), newWidth, newHeight);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        Btn_Rotate_Single_Click(doubleAngle, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    PHVideoCapture.ReleaseWriter();
                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                }
                else
                {
                    Btn_Rotate_Single_Click(doubleAngle, e);
                }
            }
            else
            {
                Btn_Rotate_Single_Click(doubleAngle, e);
            }
        }

        private void Btn_Rotate_Single_Click(double angle, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Rotate.BackColor = Color.LightGray;
            ImageList[CurrImage].UpdateImage(Transformation.Rotate(ImageList[CurrImage].ImageStructArray, angle, ImageList[CurrImage].Width, ImageList[CurrImage].Height, ImageList[CurrImage].VideoProcessing));
            EMode = EditingMode.Rotating;
        }

        /// <summary>
        /// Handles the Click event of the Btn_Subtract control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_Subtract_Click(object sender, EventArgs e)
        {
            // double[,] mask = new double[3, 3] { { 5,7, 3 }, { 6, 2, 5 }, { 9, 11, 10 } };
            // Point re = Noise.GetPointFilter(mask, FilterType.Max);

            // Point remin = Noise.GetPointFilter(mask, FilterType.Min);
            // double[,] mask = new double[3, 3] { { 5,7, 3 }, { 6, 2, 5 }, { 9, 11, 10 } };
            // Point re = Noise.GetPointFilter(mask, FilterType.Max);

            // Point remin = Noise.GetPointFilter(mask, FilterType.Min);
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            // ImageList[currImage].UpdateImage(new Noise(ImageList[currImage].Height, ImageList[currImage].Width).LinearConvolution(ImageList[currImage].ImageStructArray, 7, FilterType.Min, AddingType.Black, PostProcessing.None));
            // ImageList[currImage] = imageList[currImage].ImHistory.HistoryList[0];
            //ImageList[currImage].UpdateImage(new Noise(ImageList[currImage].Height, ImageList[currImage].Width).LinearConvolution(ImageList[currImage].ImageStructArray, 7, FilterType.Min, AddingType.Black, PostProcessing.None));

            ImageList[currImage].UpdateHistoryImage(imageList[currImage].ImHistory.Undo().ImageStructArray);            // ImageList[currImage].UpdateImage(Noise.AddUniformNoise(ImageList[currImage].ImageStructArray, 0, 255, 50));

            // FrequencyDomain freqDomain = new FrequencyDomain(imageList[currImage]);
            // freqDomain.Show();

            // double[,] testMask = { { (float)1 / 9, (float)1 / 9, (float)1 / 9 }, { (float)1 / 9, (float)1 / 9, (float)1 / 9 }, { (float)1 / 9, (float)1 / 9, (float)1 / 9 } };
            // imageList[currImage].UpdateImage(NeighborhoodOperations.Convolution(imageList[currImage].ImageStructArray, testMask, CutType.None, AddingType.Same));

            // imageList[currImage].UpdateImage(NeighborhoodOperations.AddRows_Colomns( imageList[currImage].ImageStructArray,3,AddingType.Same));
        }

        /// <summary>
        /// Handles the Click event of the Btn_RLeft control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_RLeft_Click(object sender, EventArgs e)
        {
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Height, ImageList[currImage].Width);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        Btn_RLeft_Single_Click(sender, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    Btn_RLeft_Single_Click(sender, e);
                }
            }
            else
            {
                Btn_RLeft_Single_Click(sender, e);
            }
        }

        private void Btn_RLeft_Single_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Rotate.BackColor = Color.LightGray;
            EMode = EditingMode.Rotating;
            operationName = "Image rotated left";
            ImageList[CurrImage].UpdateImage(Transformation.Rotate90Left(ImageList[CurrImage].ImageStructArray));
        }

        /// <summary>
        /// Handles the Click event of the Btn_RRight control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_RRight_Click(object sender, EventArgs e)
        {
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Height, ImageList[currImage].Width);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        Btn_RRight_Single_Click(sender, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    Btn_RRight_Single_Click(sender, e);
                }
            }
            else
            {
                Btn_RRight_Single_Click(sender, e);
            }
        }

        private void Btn_RRight_Single_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Rotate.BackColor = Color.LightGray;
            EMode = EditingMode.Rotating;
            operationName = "Image rotated right";
            ImageList[CurrImage].UpdateImage(Transformation.Rotate90Right(ImageList[CurrImage].ImageStructArray));
        }

        /// <summary>
        /// Handles the Click event of the BtnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            SaveFileDialog sf = new SaveFileDialog();
            sf.AddExtension = true;
            sf.DefaultExt = "bmp";
            sf.Filter = "BMP file (*.bmp)|*.bmp|Jpeg file (*.jpeg)|*.jpeg|P6 file (*.ppm)|*.p6|" +
                        "PNG file (*.png)|*.png|P5 file (*.pgm)|*.pgm|P3 file (*.ppm)|*.p3";
            sf.ShowDialog();
            string filePath = sf.FileName;
            int shapeindes = -1;
            int originalPixelIndex;
            if (ImageList[CurrImage].MyShaps.AllShapes.Count > 0)
            {
                Bitmap newbitmap = new Bitmap(ImageList[CurrImage].Width, ImageList[CurrImage].Height, PixelFormat.Format24bppRgb);
                unsafe
                {
                    BitmapData bmpNewD = newbitmap.LockBits(new System.Drawing.Rectangle(0, 0, ImageList[CurrImage].Width, ImageList[CurrImage].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    BitmapData bmpOldD = ImageList[CurrImage].ImageBitmap.LockBits(new System.Drawing.Rectangle(0, 0, ImageList[CurrImage].Width, ImageList[CurrImage].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    int originalExtraBytes = bmpNewD.Stride - (ImageList[CurrImage].Width * 3);
                    byte* pNew = (byte*)bmpNewD.Scan0;
                    byte* pOriginal = (byte*)bmpOldD.Scan0;

                    for (int i = 0; i < ImageList[CurrImage].Height; i++)
                    {
                        for (int j = 0; j < ImageList[CurrImage].Width; j++)
                        {
                            shapeindes = -1;
                            originalPixelIndex = (i * ImageList[CurrImage].Width * 3) + (i * originalExtraBytes) + (j * 3);
                            for (int k = 0; k < ImageList[CurrImage].MyShaps.AllShapes.Count; k++)
                            {
                                if (ImageList[CurrImage].MyShaps.AllShapes[k].PointInShape(j, i))
                                {
                                    shapeindes = k;
                                }
                            }

                            if (shapeindes != -1)
                            {
                                Color c = ImageList[CurrImage].MyShaps.AllShapes[shapeindes].FillColor;
                                pNew[originalPixelIndex] = c.B;
                                pNew[originalPixelIndex + 1] = c.G;
                                pNew[originalPixelIndex + 2] = c.R;
                            }
                            else
                            {
                                pNew[originalPixelIndex] = pOriginal[originalPixelIndex];
                                pNew[originalPixelIndex + 1] = pOriginal[originalPixelIndex + 1];
                                pNew[originalPixelIndex + 2] = pOriginal[originalPixelIndex + 2];
                            }
                        }
                    }

                    newbitmap.UnlockBits(bmpNewD);
                    ImageList[CurrImage].ImageBitmap.UnlockBits(bmpOldD);
                }
                SaveImages.SaveImage(filePath, newbitmap);

            }
            else
            {
                SaveImages.SaveImage(filePath, ImageList[CurrImage].ImageBitmap);
            }
            operationName = "Image saved";
        }

        /// <summary>
        /// Handles the Click event of the BtnMirrorH control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnMirrorH_Click(object sender, EventArgs e)
        {
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Width, ImageList[currImage].Height);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        BtnMirrorH_Single_Click(sender, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    BtnMirrorH_Single_Click(sender, e);
                }
            }
            else
            {
                BtnMirrorH_Single_Click(sender, e);
            }
        }

        private void BtnMirrorH_Single_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Rotate.BackColor = Color.LightGray;
            EMode = EditingMode.Rotating;
            operationName = "Image mirrored horizontally";
            ImageList[CurrImage].UpdateImage(Operations.Mirror(ImageList[CurrImage].ImageStructArray, true));
        }

        /// <summary>
        /// Handles the Click event of the BtnMirrorV control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnMirrorV_Click(object sender, EventArgs e)
        {
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Width, ImageList[currImage].Height);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        BtnMirrorV_Single_Click(sender, e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    BtnMirrorV_Single_Click(sender, e);
                }
            }
            else
            {
                BtnMirrorV_Single_Click(sender, e);
            }
        }

        private void BtnMirrorV_Single_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Rotate.BackColor = Color.LightGray;
            EMode = EditingMode.Rotating;
            operationName = "Image mirrored vertically";

            ImageList[CurrImage].UpdateImage(Operations.Mirror(ImageList[CurrImage].ImageStructArray, false));
        }

        /// <summary>
        /// Handles the Click event of the Btn_ShearY control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_ShearY_Click(object sender, EventArgs e)
        {
            string angle = Interaction.InputBox("Please Enter The angle of Shearing", "Shearing on Y", "0");
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    // TO EDIT TO ADD CORRECT SIZE
                    int newHeight = 0, newWidth = 0;
                    try
                    {
                        Transformation.GetWidth_Height_ShearY(ImageList[currImage].ImageStructArray, float.Parse(angle), ref newWidth, ref newHeight);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                        MessageBox.Show("Wrong angle");
                        return;
                    }
                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), ImageList[currImage].Width, ImageList[currImage].Height);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        Btn_ShearY_Single_Click(float.Parse(angle), e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                    }

                    ImageList[currImage].VideoProcessing = false;
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                    PHVideoCapture.ReleaseWriter();
                }
                else
                {
                    Btn_ShearY_Single_Click(float.Parse(angle), e);
                }
            }
            else
            {
                Btn_ShearY_Single_Click(float.Parse(angle), e);
            }
        }

        private void Btn_ShearY_Single_Click(float angle, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Shear.BackColor = Color.LightGray;
            EMode = EditingMode.Shearing;
           // if (angle != string.Empty)
            {
                operationName = "Image sheared on Y-axis";
                ImageList[CurrImage].UpdateImage(Transformation.ShearOnY(ImageList[CurrImage].ImageStructArray, angle));
            }
        }

        /// <summary>
        /// Handles the Click event of the Btn_ShearX control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Btn_ShearX_Click(object sender, EventArgs e)
        {
            string angle = Interaction.InputBox("Please Enter The angle of Shearing", "Shearing on x", "0");
            if (ImageList[currImage].IsVideo)
            {
                DialogResult result = MessageBox.Show("Do you want to process all video?", "", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    SaveFileDialog sf = new SaveFileDialog();
                    sf.AddExtension = true;
                    sf.DefaultExt = "avi";
                    sf.Filter = "AVI file (*.avi)|*.avi";
                    sf.ShowDialog();

                    // TO EDIT TO ADD CORRECT SIZE
                    int newHeight = 0, newWidth = 0;
                    try
                    {
                        Transformation.GetWidth_Height_ShearX(ImageList[currImage].ImageStructArray, float.Parse(angle), ref newWidth, ref newHeight);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                        MessageBox.Show("Wrong angle");
                        return;
                    }
                    PHVideoCapture.PHInitializeWriter((sf.FileName + '\0').ToArray(), newWidth, newHeight);

                    ImageList[currImage].VideoProcessing = true;
                    for (int i = 0; i < ImageList[currImage].NumberOfFrames - 1; i++)
                    {
                        Btn_ShearX_Single_Click(float.Parse(angle), e);
                        PHVideoCapture.RecordFrame(ImageList[currImage].ImageBitmap);

                        ImageList[currImage].ImageBitmap = new Bitmap(ImageList[currImage].Width, ImageList[currImage].Height, PixelFormat.Format24bppRgb);

                        try
                        {
                        	PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                        }
                        catch (System.Exception ex)
                        {
                            Logger.LogException(ex);
                        }
                       
                    }

                    ImageList[currImage].VideoProcessing = false;
                    PHVideoCapture.ReleaseWriter();
                    ImageList[currImage].UpdateImage(ImageList[currImage].ImageBitmap);
                }
                else
                {
                    Btn_ShearX_Single_Click(float.Parse(angle), e);
                }
            }
            else
            {
                Btn_ShearX_Single_Click(float.Parse(angle), e);
            }
        }

        private void Btn_ShearX_Single_Click(float angle, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            this.ClearAllButtons();
            this.SC_Shear.BackColor = Color.LightGray;
            EMode = EditingMode.Shearing;
          //  if (angle != string.Empty)
            {
                operationName = "Image sheared on X-axis with angle " + angle.ToString();
                ImageList[CurrImage].UpdateImage(Transformation.ShearOnX(ImageList[CurrImage].ImageStructArray, angle));
            }
        }
        #endregion

        #region History
        /// <summary>
        /// Handles the Click event of the undoToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void UndoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImageList[currImage].UpdateHistoryImage(imageList[currImage].ImHistory.Undo().ImageStructArray);
            this.phPictureStringList1.Undo();
        }

        /// <summary>
        /// Handles the Click event of the redoToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void RedoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ImageList[currImage].UpdateHistoryImage(imageList[currImage].ImHistory.Redo().ImageStructArray);
            this.phPictureStringList1.Redo();
        }

        /// <summary>
        /// Handles the Click event of the cloneToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void CloneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                OpenImage(Main.imageList[Main.currImage].ImageBitmap);
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }

            if (imageList.Count > 0)
            {
                this.EnableImageOperations();
            }
            UpdateChannelsPic();
            UpdateImageInfo();

        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the listBox1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void HistoryListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Main.SelectedIndexChange)
            {
                // this.historyListBox.SelectedIndex = Main.imageList[Main.currImage].ImHistory.CurrentInHistory;
                Main.SelectedIndexChange = false;
            }
            else
            {
                Main.imageList[currImage].UpdateHistoryImage(Main.imageList[Main.currImage].ImHistory.HistoryList[this.historyListBox.SelectedIndex].ImageStructArray);
            }
        }

        /// <summary>
        /// Handles the ActiveIndexChanged event of the phPictureStringList1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void phPictureStringList1_ActiveIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (Main.SelectedIndexChange)
                {
                    // this.historyListBox.SelectedIndex = Main.imageList[Main.currImage].ImHistory.CurrentInHistory;
                    Main.SelectedIndexChange = false;
                }
                else
                {
                    Main.imageList[currImage].UpdateHistoryImage(Main.imageList[Main.currImage].ImHistory.HistoryList[this.phPictureStringList1.ActiveIndex].ImageStructArray);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }
        #endregion

        /// <summary>
        /// Handles the Click event of the helpToolStripMenuItem1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void HelpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //videoThread = new Thread(new ThreadStart(UpdatePicboxWithFrames));
            //videoThread.Start();
            //Help.ShowHelp(this, "Help.jpg");
            HelpForm help = new HelpForm();
            help.Show();
        }

        public void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //videoThread.Abort();
            //operationName = "Captured new frame from video.";
            //imageList[currImage].UpdateImage(imageList[currImage].ImageBitmap);
            //AboutForm form = new AboutForm();
            //form.Show();
            PHLogo logo = new PHLogo();
            logo.Show();
        }

        /// <summary>
        /// Handles the Click event of the pictureBox11 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PictureBox11_Click(object sender, EventArgs e)
        {
            return;
        }

        /// <summary>
        /// Handles the MouseHover event of the pictureBox11 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PictureBox11_MouseHover(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            pb.Image = Image.FromFile(@"Icons\" + pb.Name.Substring(4) + "Over.png");
        }

        /// <summary>
        /// Handles the MouseLeave event of the Pcb_Close control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Close_MouseLeave(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            pb.Image = Image.FromFile(@"Icons\" + pb.Name.Substring(4) + ".png");
        }

        /// <summary>
        /// Handles the Click event of the Pcb_Max control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Max_Click(object sender, EventArgs e)
        {
            // if (this.WindowState != FormWindowState.Maximized)
            // {
            //    this.WindowState = FormWindowState.Maximized;
            //    this.Pcb_Min.Visible = false;
            // }
            // else
            // {
            //    this.WindowState = FormWindowState.Normal;
            //    this.Pcb_Min.Visible = true;
            // }
            this.MaximizeTheForm();
        }

        /// <summary>
        /// Handles the Click event of the Pcb_Close control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the Pcb_Min control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Min_Click(object sender, EventArgs e)
        {
            this.formLocation = this.Location;
            this.formSize = this.Size;
            this.isMinmize = true;
            this.DecreaseFormSize();
            this.WindowState = FormWindowState.Minimized;
            this.Location = this.formLocation;
            this.Size = this.formSize;
            this.isMinmize = false;
        }

        /// <summary>
        /// Handles the MouseEnter event of the Pcb_Zoom control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Zoom_MouseEnter(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            if (pb.BorderStyle == BorderStyle.None)
            {
                pb.BorderStyle = BorderStyle.FixedSingle;
            }
        }

        /// <summary>
        /// Handles the MouseLeave event of the Pcb_Zoom control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Zoom_MouseLeave(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            if (pb.BorderStyle == BorderStyle.FixedSingle)
            {
                pb.BorderStyle = BorderStyle.None;
            }
        }

        /// <summary>
        /// Handles the Click event of the Pcb_Zoom control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Pcb_Zoom_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            PictureBox pb = (PictureBox)sender;

            if (pb.BorderStyle == BorderStyle.Fixed3D)
            {
                pb.BorderStyle = BorderStyle.None;
                EMode = EditingMode.Nothing;
                VerticalToolStrip.Visible = false;
                return;
            }
            else
            {
                this.DeactivateTools();
                pb.BorderStyle = BorderStyle.Fixed3D;
            }


            switch (pb.Name.Substring(4))
            {
                case "Select":
                    ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.NONE;
                    EMode = EditingMode.Nothing;
                    HandleGUIEvents.CreateDrawToolStrip(ref this.VerticalToolStrip);
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Crop":
                    imageList[currImage].BackupImageArray();
                    EMode = EditingMode.Cropping;
                    HandleGUIEvents.CreateCropToolStrip(ref this.VerticalToolStrip);
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Cirlce":
                    operationName = "Circle drawn.";
                    ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.CIRCLE;
                    HandleGUIEvents.CreateDrawToolStrip(ref this.VerticalToolStrip);
                    EMode = EditingMode.Drawing;
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Ellipse":
                    operationName = "Ellipse drawn.";
                    ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.ELLIPSE;
                    HandleGUIEvents.CreateDrawToolStrip(ref this.VerticalToolStrip);
                    EMode = EditingMode.Drawing;
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Rectangle":
                    operationName = "Rectangle drawn.";
                    ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.RECTANGLE;
                    HandleGUIEvents.CreateDrawToolStrip(ref this.VerticalToolStrip);
                    EMode = EditingMode.Drawing;
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Polygon":
                    operationName = "Polygon drawn.";
                    ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.POLYGON;
                    HandleGUIEvents.CreateDrawToolStrip(ref this.VerticalToolStrip);
                    EMode = EditingMode.Drawing;
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Pen":
                    operationName = "Freehand shape drawn.";
                    ImageList[Main.CurrImage].MyShaps.ShapeToBeDrawn = SHAPENAME.FreeMove;
                    this.Invalidate();
                    HandleGUIEvents.CreateDrawToolStrip(ref this.VerticalToolStrip);
                    EMode = EditingMode.Drawing;
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Hand":
                    EMode = EditingMode.Hand;
                    HandleGUIEvents.CreateTranslateToolStrip(ref this.VerticalToolStrip);
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Rotate":
                    operationName = "Rotatation.";
                    EMode = EditingMode.Rotating;
                    HandleGUIEvents.CreateRotateToolStrip(ref this.VerticalToolStrip);
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "Shear":
                    operationName = "Shearing";                    
                    EMode = EditingMode.Shearing;
                    HandleGUIEvents.CreateShearToolStrip(ref this.VerticalToolStrip);
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
                case "MainZoom":
                    operationName = "Zoom.";                                     
                    EMode = EditingMode.Resizing;
                    HandleGUIEvents.CreateZoomToolStrip(ref this.VerticalToolStrip);
                    VerticalToolStrip.Invalidate();
                    VerticalToolStrip.BringToFront();
                    this.Invalidate();
                    break;
            }
            //EMode = EditingMode.Cropping;
            // Main.MainCursor = System.Windows.Forms.Cursors.Hand;
            //this.Cursor = System.Windows.Forms.Cursors.Hand;

        }

        /// <summary>
        /// Deactivates the tools.
        /// </summary>
        private void DeactivateTools()
        {
            this.Pcb_Cirlce.BorderStyle = BorderStyle.None;
            this.Pcb_Ellipse.BorderStyle = BorderStyle.None;
            this.Pcb_Rectangle.BorderStyle = BorderStyle.None;
            this.Pcb_Pen.BorderStyle = BorderStyle.None;
            this.Pcb_Polygon.BorderStyle = BorderStyle.None;
            this.Pcb_Select.BorderStyle = BorderStyle.None;
            this.Pcb_Crop.BorderStyle = BorderStyle.None;
            this.Pcb_Hand.BorderStyle = BorderStyle.None;
            this.Pcb_MainZoom.BorderStyle = BorderStyle.None;
            this.Pcb_Shear.BorderStyle = BorderStyle.None;
            this.Pcb_Rotate.BorderStyle = BorderStyle.None;
        }

        /// <summary>
        /// Decreases the size of the form.
        /// </summary>
        private void DecreaseFormSize()
        {
            while (this.Size.Height > 2 && this.Size.Width > 2)
            {
                this.Location = new Point(this.Location.X + 5, this.Location.Y + 5);
                this.Size -= new Size(10, 10);
            }
        }

        /// <summary>
        /// Handles the Click event of the phTabContainer1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PhTabContainer1_Click(object sender, EventArgs e)
        {
            currImage = this.phTabContainer1.ActiveTabIndex;
        }

        /// <summary>
        /// Handles the Click event of the NotchBandToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void NotchBandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (imageList.Count == 0)
            {
                MessageBox.Show("Please open an image first");
                return;
            }
        }

        /// <summary>
        /// Centers the form.
        /// </summary>
        private void CenterTheForm()
        {
            int boundWidth = Screen.PrimaryScreen.Bounds.Width;
            int boundHeight = Screen.PrimaryScreen.Bounds.Height;
            this.Size = new Size((int)(boundWidth / 1.2), (int)(boundHeight / 1.2));
            this.Location = new Point((boundWidth / 2) - (this.Size.Width / 2), (boundHeight / 2) - (this.Size.Height / 2));
        }

        /// <summary>
        /// Maximizes the form.
        /// </summary>
        private void MaximizeTheForm()
        {
            if (!this.maxmized)
            {
                this.formLocation = this.Location;
                this.formSize = this.Size;
                int boundWidth = Screen.PrimaryScreen.Bounds.Width;
                int boundHeight = Screen.PrimaryScreen.Bounds.Height;
                this.Location = new Point(0, 0);
                this.Size = new Size(boundWidth, boundHeight - 40);
                this.maxmized = true;
            }
            else
            {
                this.Size = this.formSize;
                this.Location = this.formLocation;
                this.maxmized = false;
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the TextBox1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TextBox1_TextChanged(object sender, EventArgs e)
        {
            return;
        }

        /// <summary>
        /// Handles the Scroll event of the amplitudeTrakBar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void AmplitudeTrakBar_Scroll(object sender, EventArgs e)
        {
            this.TxtAmplitude.Text = this.amplitudeTrakBar.Value.ToString();
        }

        /// <summary>
        /// Handles the Scroll event of the FxTrackBar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FxTrackBar_Scroll(object sender, EventArgs e)
        {
            this.TxtFx.Text = this.FxTrackBar.Value.ToString();
        }

        /// <summary>
        /// Handles the Scroll event of the FYTrackBar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FYTrackBar_Scroll(object sender, EventArgs e)
        {
            this.TxtFY.Text = this.FYTrackBar.Value.ToString();
        }

        /// <summary>
        /// Handles the Scroll event of the PxtrackBar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PxtrackBar_Scroll(object sender, EventArgs e)
        {
            this.TxtPx.Text = (this.PxtrackBar.Value / 10.0).ToString();
        }

        /// <summary>
        /// Handles the Scroll event of the PYtrackBar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void PYtrackBar_Scroll(object sender, EventArgs e)
        {
            this.TxtPY.Text = (this.PYtrackBar.Value / 2).ToString();
        }

        /// <summary>
        /// Handles the Click event of the BtnPeriodicNoise control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BtnPeriodicNoise_Click(object sender, EventArgs e)
        {
            Main.imageList[Main.currImage].UpdateImage(Noise.AddPeriodicNoise(Main.imageList[Main.currImage].ImageStructArray, Convert.ToByte(this.TxtAmplitude.Text), Convert.ToDouble(this.TxtFx.Text), Convert.ToDouble(this.TxtFY.Text), Convert.ToDouble(this.TxtPx.Text), Convert.ToDouble(this.TxtPY.Text)));
        }

        /// <summary>
        /// Handles the VisibleChanged event of the grbInputValues control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void GrbInputValues_VisibleChanged(object sender, EventArgs e)
        {
            GroupBox gb = (GroupBox)sender;
            if (gb.Visible)
            {
                if (gb.Name == this.grbInputValues.Name)
                {
                    this.groupBoxPeriodicNoise.Visible = false;
                }
                else if (gb.Name == this.groupBoxPeriodicNoise.Name)
                {
                    this.grbInputValues.Visible = false;
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the binaryThersholdToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BinaryThersholdToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ThreSholdBlackWhite form = new ThreSholdBlackWhite("binary");
            form.Show();
        }

        /// <summary>
        /// Handles the Click event of the morphologyToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MorphologyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Morphology form = new Morphology();
            form.Show();
        }

        /// <summary>
        /// Sets the group box controls to invisible
        /// </summary>
        private void SetGrbInputValuesInvisible()
        {
            foreach (Control item in this.grbInputValues.Controls)
            {
                item.Visible = false;
            }

            this.btnGo.Visible = true;
            this.btnHideGrbInputValues.Visible = true;
        }

        private void Pcb_New_Click(object sender, EventArgs e)
        {
            NewImage newImage = new NewImage();
            newImage.Show();
        }

        /// <summary>
        /// Handles the Click event of the fastToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FastToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Quantization";
            this.lblGrbInputValues1.Visible = this.txtGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Quantization value";
            InputValueper = InputValuesEnum.Quantization;
        }

        #region Zoom
        /// <summary>
        /// Handles the Click event of the toolStripMenuItem6 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 0.1;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem7 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 0.25;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem8 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 0.5;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem9 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 0.75;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem10 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 1;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem11 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 1.5;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem12 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 2;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem13 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 4;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the toolStripMenuItem14 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void toolStripMenuItem14_Click(object sender, EventArgs e)
        {
            ImageEvents.factorZoom = 5;
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.PictureBoxZoomWH(imageList[currImage].ImageBitmap);
        }

        /// <summary>
        /// Handles the Click event of the zoomInToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void zoomInToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //PictureBox pb = (PictureBox)sender;

            //if (pb.BorderStyle == BorderStyle.Fixed3D)
            //{
            //    pb.BorderStyle = BorderStyle.None;
            //    EMode = EditingMode.Nothing;
            //    VerticalToolStrip.Visible = false;
            //    return;
            //}
            //else
            //{
            //    this.DeactivateTools();
            //    pb.BorderStyle = BorderStyle.Fixed3D;
            //}

            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.ZoomIn(((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image, imageList[currImage].Width, imageList[currImage].Height);
        }

        /// <summary>
        /// Handles the Click event of the zoomOutToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public void zoomOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image = ImageEvents.ZoomOut(((PictureBox)this.phTabContainer1.tempPanel.Controls[0]).Image, imageList[currImage].Width, imageList[currImage].Height);
        }

        #endregion

        /// <summary>
        /// Handles the Click event of the ToolStripMean1D control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ToolStripMean1D_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            InputValueper = InputValuesEnum.MeanFilter1D;
            this.grbInputValues.Visible = true;
            this.txtGrbInputValues1.Visible = this.lblGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Mask Value";
            this.grbInputValues.Text = "Mean filter 1D";
        }

        /// <summary>
        /// Handles the Click event of the ToolStripGaussian1D control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ToolStripGaussian1D_Click(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            operationName = "Gaussian filter with sigma: ";
            InputValueper = InputValuesEnum.GaussianFilter1D;
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Gaussian filter";
            this.txtGrbInputValues1.Visible = this.lblGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Sigma value";
        }

        /// <summary>
        /// Handles the Click event of the noiseDetectionToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void noiseDetectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NoiseDetection nd = new NoiseDetection(imageList[currImage].ImageBitmap);
            nd.Show();
        }

        /// <summary>
        /// Handles the Click event of the slideShowToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void slideShowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // panelSlidShow.BringToFront();

            // panelSlidShow.Size = this.Size;
            // panelSlidShow.Location = this.Location;
            // panelSlidShow.Dock = DockStyle.Fill;
            // pictureBox2.Dock = DockStyle.Fill;
            // for (int i = 0; i < imageList.Count; i++)
            //  {
            //      panelSlidShow.BackgroundImage =  imageList[i].ImageBitmap;
            //  pictureBox2.Image = imageList[i].ImageBitmap;
            // this.Invalidate();

            //     System.Threading.Thread.Sleep(3000);    
            // }
            // this.panelSlidShow.Visible = false;
        }

        /// <summary>
        /// Handles the Click event of the fromFolderToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void fromFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SlideShowForm slideshow = new SlideShowForm(SlideShowType.FromFolder);
            slideshow.Show();
            this.AddOwnedForm(slideshow);
        }

        /// <summary>
        /// Handles the Click event of the openedImagesToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void openedImagesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Main.ImageList.Count < 1)
            {
                MessageBox.Show("Please open an image first.");
                this.Close();
                return;
            }

            SlideShowForm slideshow = new SlideShowForm(SlideShowType.FromCurrentImages);
            slideshow.Show();
            this.AddOwnedForm(slideshow);
        }

        /// <summary>
        /// Handles the Click event of the puzzleGameToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void puzzleGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
            puzzleGameForm form = new puzzleGameForm();
            form.Show();
        }

        /// <summary>
        /// Handles the 1 event of the puzzleGameToolStripMenuItem_Click control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void puzzleGameToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            puzzleGameForm form = new puzzleGameForm();
            form.Show();
        }

        /// <summary>
        /// Handles the Scroll event of the TrkResize control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void TrkResize_Scroll(object sender, EventArgs e)
        {
            if (Main.ImageList.Count == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            int height = 0;
            int width = 0;

            height = (this.TrkResize.Value + 1) * ImageList[currImage].Height;
            width = (this.TrkResize.Value + 1) * ImageList[currImage].Width;

            this.txtGrbInputValues2.Text = height.ToString();
            this.txtGrbInputValues3.Text = width.ToString();
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the cmbResizeAlgorithm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void cmbResizeAlgorithm_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbResizeAlgorithm.SelectedIndex == 2)
            {
                this.CmbInterpolationMode.Enabled = true;
            }
            else
            {
                this.CmbInterpolationMode.Enabled = false;
            }
        }

        private void sepiaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            operationName = "Sepia Effect";
            imageList[currImage].UpdateImage(CalcOperation.SepiaEffect(imageList[currImage].ImageStructArray));
        }

        private void retinxToolStripMenuItem_Click(object sender, EventArgs e)
        {
            double[] sigma = { 15, 80, 250 };
            double[] weight = { 0.33F, 0.33F, 0.33F };
            matRetinx.retinx rtnx = new matRetinx.retinx();
            //  matlabRetinx.Class2 rtnx = new Class2();
            imageList[currImage].UpdateImage(MatlabOperations.Retinex(rtnx, imageList[currImage].ImageStructArray, sigma, weight));
        }

        private void gaussian1DToolStripMenuItem_Click(object sender, EventArgs e)
        {
            matlabRetinx.Class2 rtnx = new Class2();
            double sigma = 3;
            imageList[currImage].UpdateImage(MatlabOperations.Gaussain1D(rtnx, imageList[currImage].ImageStructArray, sigma));
        }

        #region Video operations
        private void UpdatePicboxWithFrames()
        {
            while (true)
            {
                this.canPause = true;
                Thread.Sleep(waitMS);
                this.canPause = false;
                if (ImageList[CurrImage].CurrFrameIndex >= ImageList[CurrImage].NumberOfFrames - 1)
                {
                    this.canPause = true;
                    videoThread = null;
                    return;
                }

                UpdateFrameHandler();
                ImageList[CurrImage].CurrFrameIndex++;
                TKB_Vedio.Value = ImageList[currImage].CurrFrameIndex;
            }
        }

        private void Main_UpdateFrameHandler()
        {
            this.SetTrackBar();
            try
            {
                PHVideoCapture.QueryFrame(ImageList[currImage].ImageBitmap);
                ((PictureBox)MainTabContainer.tempPanel.Controls[0]).Image = ImageList[CurrImage].ImageBitmap;
            }
            catch
            {
                return;
            }
        }

        public void Play_Click(object sender, EventArgs e)
        {
            if (videoThread != null)
            {
                return;
            }

            ImageList[currImage].CurrFrameIndex = 0;
            PHVideoCapture.PHSeekVideo(0.0);

            videoThread = new Thread(new ThreadStart(UpdatePicboxWithFrames));
            videoThread.Start();
        }

        public void Pause_Click(object sender, EventArgs e)
        {
            if (videoThread == null)
            {
                return;
            }

            while (!this.canPause) ;
            videoThread.Abort();
            operationName = "Captured new frame from video.";
            imageList[currImage].UpdateImage(imageList[currImage].ImageBitmap);
            videoThread = null;
        }

        public void SpeedUP_Click(object sender, EventArgs e)
        {
            waitMS = waitMS - 10 < 10 ? 10 : waitMS - 10;
        }

        public void SpeedDown_Click(object sender, EventArgs e)
        {
            waitMS += 10;
        }

        public void Capture_Click(object sender, EventArgs e)
        {
            if (videoThread != null)
            {
                while (!this.canPause) ;
                videoThread.Abort();
            }

            OpenImage(imageList[currImage].ImageBitmap);
        }

        public void SetTrackBar()
        {
            if (ImageList[currImage].IsVideo)
            {
                TKB_Vedio.Maximum = ImageList[currImage].NumberOfFrames;
                TKB_Vedio.Value = ImageList[currImage].CurrFrameIndex <= 0 ? 1 : ImageList[currImage].CurrFrameIndex;
            }
        }

        void TKB_Vedio_Scroll(object sender, System.EventArgs e)
        {
            ImageList[CurrImage].CurrFrameIndex = TKB_Vedio.Value;
            trackValue = TKB_Vedio.Value;
            tracking = true;
            videoTrackCounter = 0;
            // while (canPause) ;
            // PHVideoCapture.PHSeekVideo((double)TKB_Vedio.Value);
        }
        #endregion

        private void DisableImageOperations()
        {
            saveToolStripMenuItem.Enabled = false;
            saveAsToolStripMenuItem.Enabled = false;
            cloneToolStripMenuItem.Enabled = false;
            undoToolStripMenuItem.Enabled = false;
            redoToolStripMenuItem.Enabled = false;
            histogramToolStripMenuItem.Enabled = false;
            openedImagesToolStripMenuItem.Enabled = false;
            quantizationToolStripMenuItem.Enabled = false;
            shearOnXToolStripMenuItem.Enabled = false;
            shToolStripMenuItem.Enabled = false;
            horizontalToolStripMenuItem.Enabled = false;
            verticalToolStripMenuItem.Enabled = false;
            leftToolStripMenuItem.Enabled = false;
            toolStripMenuItem2.Enabled = false;
            byAngleToolStripMenuItem.Enabled = false;
            morphologyToolStripMenuItem.Enabled = false;
            resizeToolStripMenuItem1.Enabled = false;
            sepiaToolStripMenuItem.Enabled = false;
            greyscaleToolStripMenuItem.Enabled = false;
            notToolStripMenuItem.Enabled = false;
            calculationToolStripMenuItem.Enabled = false;
            zoomToolStripMenuItem.Enabled = false;
            gammaCorrectionToolStripMenuItem.Enabled = false;
            brightnessAndContrastToolStripMenuItem.Enabled = false;
            pixelOperationsGraphToolStripMenuItem.Enabled = false;
            histogramMatchingToolStripMenuItem.Enabled = false;
            histogramEqualizationToolStripMenuItem.Enabled = false;
            histogramLocalEqlizationToolStripMenuItem.Enabled = false;
            effectsToolStripMenuItem.Enabled = false;
            thersholdToolStripMenuItem.Enabled = false;
            toolStripMenuItem3.Enabled = false;
            toolStripMenuItem1.Enabled = false;
            edgeDetectionToolStripMenuItem.Enabled = false;
            customConvolutionToolStripMenuItem.Enabled = false;
            cannyFilterToolStripMenuItem.Enabled = false;
            toolStripMenuItem4.Enabled = false;
            noiseToolStripMenuItem.Enabled = false;
            noiseFilterToolStripMenuItem.Enabled = false;
            noiseDetectionToolStripMenuItem.Enabled = false;
            fourierEffectsToolStripMenuItem.Enabled = false;
            fourierTranslationToolStripMenuItem.Enabled = false;
            retinexToolStripMenuItem.Enabled = false;
            gaussian1DToolStripMenuItem.Enabled = false;
            spyMessagingToolStripMenuItem.Enabled = false;
            puzzleGameToolStripMenuItem.Enabled = false;
            Pcb_Cirlce.Enabled = false;
            Pcb_Select.Enabled = false;
            Pcb_Ellipse.Enabled = false;
            Pcb_Crop.Enabled = false;
            Pcb_Rectangle.Enabled = false;
            Pcb_Polygon.Enabled = false;
            Pcb_Pen.Enabled = false;
            Pcb_Rotate.Enabled = false;
            Pcb_Shear.Enabled = false;
            Pcb_Hand.Enabled = false;
            Pcb_Save.Enabled = false;
            Pcb_Undo.Enabled = false;
            Pcb_Redo.Enabled = false;
            translateToolStripMenuItem.Enabled = false;
            resizeToolStripMenuItem.Enabled = false;
            shToolStripMenuItem.Enabled = false;
            rotateToolStripMenuItem.Enabled = false;
            retinxToolStripMenuItem.Enabled = false;
            sarpingToolStripMenuItem.Enabled = false;
            cropToolStripMenuItem.Enabled = false;
            this.Pcb_MainZoom.Enabled = false;
            historyToolStripMenuItem.Enabled = false;
            channelsToolStripMenuItem.Enabled = false;
            imageInfoToolStripMenuItem.Enabled = false;
            replaceColorToolStripMenuItem.Enabled = false;
            printToolStripMenuItem.Enabled = false;
            printPreviewToolStripMenuItem.Enabled = false;
            setAsBackgroundToolStripMenuItem.Enabled = false;
            fastToolStripMenuItem.Enabled = false;
            interfaceToolStripMenuItem.Enabled = false;
        }

        private void EnableImageOperations()
        {
            saveToolStripMenuItem.Enabled = true;
            saveAsToolStripMenuItem.Enabled = true;
            cloneToolStripMenuItem.Enabled = true;
            undoToolStripMenuItem.Enabled = true;
            redoToolStripMenuItem.Enabled = true;
            histogramToolStripMenuItem.Enabled = true;
            openedImagesToolStripMenuItem.Enabled = true;
            quantizationToolStripMenuItem.Enabled = true;
            shearOnXToolStripMenuItem.Enabled = true;
            shToolStripMenuItem.Enabled = true;
            horizontalToolStripMenuItem.Enabled = true;
            verticalToolStripMenuItem.Enabled = true;
            leftToolStripMenuItem.Enabled = true;
            toolStripMenuItem2.Enabled = true;
            byAngleToolStripMenuItem.Enabled = true;
            morphologyToolStripMenuItem.Enabled = true;
            resizeToolStripMenuItem1.Enabled = true;
            sepiaToolStripMenuItem.Enabled = true;
            greyscaleToolStripMenuItem.Enabled = true;
            notToolStripMenuItem.Enabled = true;
            calculationToolStripMenuItem.Enabled = true;
            zoomToolStripMenuItem.Enabled = true;
            gammaCorrectionToolStripMenuItem.Enabled = true;
            brightnessAndContrastToolStripMenuItem.Enabled = true;
            pixelOperationsGraphToolStripMenuItem.Enabled = true;
            histogramMatchingToolStripMenuItem.Enabled = true;
            histogramEqualizationToolStripMenuItem.Enabled = true;
            histogramLocalEqlizationToolStripMenuItem.Enabled = true;
            effectsToolStripMenuItem.Enabled = true;
            thersholdToolStripMenuItem.Enabled = true;
            toolStripMenuItem3.Enabled = true;
            toolStripMenuItem1.Enabled = true;
            edgeDetectionToolStripMenuItem.Enabled = true;
            customConvolutionToolStripMenuItem.Enabled = true;
            cannyFilterToolStripMenuItem.Enabled = true;
            toolStripMenuItem4.Enabled = true;
            noiseToolStripMenuItem.Enabled = true;
            noiseFilterToolStripMenuItem.Enabled = true;
            noiseDetectionToolStripMenuItem.Enabled = true;
            fourierEffectsToolStripMenuItem.Enabled = true;
            fourierTranslationToolStripMenuItem.Enabled = true;
            retinexToolStripMenuItem.Enabled = true;
            gaussian1DToolStripMenuItem.Enabled = true;
            spyMessagingToolStripMenuItem.Enabled = true;
            puzzleGameToolStripMenuItem.Enabled = true;
            Pcb_Cirlce.Enabled = true;
            Pcb_Select.Enabled = true;
            Pcb_Ellipse.Enabled = true;
            Pcb_Crop.Enabled = true;
            Pcb_Rectangle.Enabled = true;
            Pcb_Polygon.Enabled = true;
            Pcb_Pen.Enabled = true;
            Pcb_Rotate.Enabled = true;
            Pcb_Shear.Enabled = true;
            Pcb_Hand.Enabled = true;
            this.Pcb_MainZoom.Enabled = true;
            Pcb_Save.Enabled = true;
            Pcb_Undo.Enabled = true;
            Pcb_Redo.Enabled = true;
            translateToolStripMenuItem.Enabled = true;
            resizeToolStripMenuItem.Enabled = true;
            shToolStripMenuItem.Enabled = true;
            rotateToolStripMenuItem.Enabled = true;
            retinxToolStripMenuItem.Enabled = true;
            sarpingToolStripMenuItem.Enabled = true;
            cropToolStripMenuItem.Enabled = true;
            historyToolStripMenuItem.Enabled = true;
            channelsToolStripMenuItem.Enabled = true;
            imageInfoToolStripMenuItem.Enabled = true;
            replaceColorToolStripMenuItem.Enabled = true;
            printToolStripMenuItem.Enabled = true;
            printPreviewToolStripMenuItem.Enabled = true;
            setAsBackgroundToolStripMenuItem.Enabled = true;
            fastToolStripMenuItem.Enabled = true;
            interfaceToolStripMenuItem.Enabled = true;
        }

        private void historyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!phTabContainer3.tabs.Contains(HistoryTab))
            {
                phTabContainer3.ResetTabs();
                phTabContainer3.Add("History");
                HistoryTab = phTabContainer3.tabs[phTabContainer3.tabs.Count - 1];
                this.HistoryTab.Panel.Controls.Add(this.phPictureStringList1);
                phTabContainer3.UpdateViewPanel();
            }
            ((ToolStripMenuItem)sender).Checked = true;
            HistoryTab.SetActive();
        }

        private void channelsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!phTabContainer3.tabs.Contains(ChannelsTab))
            {
                phTabContainer3.ResetTabs();
                StartChannels();
                phTabContainer3.UpdateViewPanel();
                UpdateChannelsPic();

            }
            ((ToolStripMenuItem)sender).Checked = true;
            ChannelsTab.SetActive();
        }

        private void imageInfoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!phTabContainer3.tabs.Contains(PhotoInfoTab))
            {
                phTabContainer3.ResetTabs();
                this.phTabContainer3.Add("Image Info");
                PhotoInfoTab = this.phTabContainer3.tabs[phTabContainer3.tabs.Count - 1];
                PhotoInfoTab.Panel.Controls.Add(Info.Panel);
                phTabContainer3.UpdateViewPanel();
            }
            ((ToolStripMenuItem)sender).Checked = true;
            PhotoInfoTab.SetActive();
        }

        private void VideoTrackTimer_Tick(object sender, EventArgs e)
        {
            if (videoTrackCounter++ == 2 && tracking)
            {
                while (canPause) ;
                PHVideoCapture.PHSeekVideo(trackValue);
                // MessageBox.Show(trackValue.ToString());
                tracking = false;
            }
        }

        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.WindowState != FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Maximized;
                this.Pcb_Min.Visible = false;
            }
            else
            {
                this.WindowState = FormWindowState.Normal;
                this.Pcb_Min.Visible = true;
            }
        }

        /// <summary>
        /// Handles the Click event of the colorsThersholdToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void colorsThersholdToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ThreSholdBlackWhite form = new ThreSholdBlackWhite("color");
            form.Show();
        }

        private void replaceColorToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void cutoffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Color clr = ShowColorsForm();
            operationName = " Replace Color R:" + clr.R + "   G:" + clr.G + "   B:" + clr.B;
            imageList[currImage].UpdateImage(CalcOperation.AddColor2image(imageList[currImage].ImageStructArray, clr, PostProcessing.CuttOff));
        }

        private void normalizationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Color clr = ShowColorsForm();
            operationName = " Replace Color R:" + clr.R + "   G:" + clr.G + "   B:" + clr.B;
            imageList[currImage].UpdateImage(CalcOperation.AddColor2image(imageList[currImage].ImageStructArray, clr, PostProcessing.Normalization));
        }

        private void setAsBackgroundToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DImage.ImagesCount == 0)
            {
                MessageBox.Show("Please open an image first.");
                return;
            }

            SaveFileDialog sf = new SaveFileDialog();
            sf.AddExtension = true;
            sf.DefaultExt = "bmp";
            sf.Filter = "BMP file (*.bmp)|*.bmp|Jpeg file (*.jpeg)|*.jpeg|P6 file (*.ppm)|*.p6|" +
                        "PNG file (*.png)|*.png|P5 file (*.pgm)|*.pgm|P3 file (*.ppm)|*.p3";
            sf.Title = "Please, Save the image First";
            sf.ShowDialog();
            string filePath = sf.FileName;
            int shapeindes = -1;
            int originalPixelIndex;
            if (ImageList[CurrImage].MyShaps.AllShapes.Count > 0)
            {
                Bitmap newbitmap = new Bitmap(ImageList[CurrImage].Width, ImageList[CurrImage].Height, PixelFormat.Format24bppRgb);
                unsafe
                {
                    BitmapData bmpNewD = newbitmap.LockBits(new System.Drawing.Rectangle(0, 0, ImageList[CurrImage].Width, ImageList[CurrImage].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    BitmapData bmpOldD = ImageList[CurrImage].ImageBitmap.LockBits(new System.Drawing.Rectangle(0, 0, ImageList[CurrImage].Width, ImageList[CurrImage].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    int originalExtraBytes = bmpNewD.Stride - (ImageList[CurrImage].Width * 3);
                    byte* pNew = (byte*)bmpNewD.Scan0;
                    byte* pOriginal = (byte*)bmpOldD.Scan0;

                    for (int i = 0; i < ImageList[CurrImage].Height; i++)
                    {
                        for (int j = 0; j < ImageList[CurrImage].Width; j++)
                        {
                            shapeindes = -1;
                            originalPixelIndex = (i * ImageList[CurrImage].Width * 3) + (i * originalExtraBytes) + (j * 3);
                            for (int k = 0; k < ImageList[CurrImage].MyShaps.AllShapes.Count; k++)
                            {
                                if (ImageList[CurrImage].MyShaps.AllShapes[k].PointInShape(j, i))
                                {
                                    shapeindes = k;
                                }
                            }

                            if (shapeindes != -1)
                            {
                                Color c = ImageList[CurrImage].MyShaps.AllShapes[shapeindes].FillColor;
                                pNew[originalPixelIndex] = c.B;
                                pNew[originalPixelIndex + 1] = c.G;
                                pNew[originalPixelIndex + 2] = c.R;
                            }
                            else
                            {
                                pNew[originalPixelIndex] = pOriginal[originalPixelIndex];
                                pNew[originalPixelIndex + 1] = pOriginal[originalPixelIndex + 1];
                                pNew[originalPixelIndex + 2] = pOriginal[originalPixelIndex + 2];
                            }
                        }
                    }

                    newbitmap.UnlockBits(bmpNewD);
                    ImageList[CurrImage].ImageBitmap.UnlockBits(bmpOldD);
                }
                SaveImages.SaveImage(filePath, newbitmap);

            }
            else
            {
                SaveImages.SaveImage(filePath, ImageList[CurrImage].ImageBitmap);
            }
            operationName = "Image saved";
            DesktopBackground.SetWallpaper(filePath);
        }

        public void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog dlg = new PrintPreviewDialog();
            dlg.Document = printDoc;
            dlg.ShowDialog();
        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printDoc.Print();
        }

        public void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            Point ulCorner = new Point(100, 100);
            e.Graphics.DrawImage(ImageList[currImage].ImageBitmap, ulCorner);
        }

        private void fastToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            this.SetGrbInputValuesInvisible();
            this.grbInputValues.Visible = true;
            this.grbInputValues.Text = "Quantization";
            this.lblGrbInputValues1.Visible = this.txtGrbInputValues1.Visible = true;
            this.lblGrbInputValues1.Text = "Quantization value";
            InputValueper = InputValuesEnum.Quantization;
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                PHVideoCapture.ReleaseVideoCapture();
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        private void InitCamera()
        {
            int width = 0, height = 0, cameraInitialized = 0;
            PHVideoCapture.PHInitializeCameraCapture(ref width, ref height, ref cameraInitialized);
            if (cameraInitialized == 0)
            {
                MessageBox.Show("Unable to start up camera.");
                return;
            }

            Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            PHVideoCapture.QueryFrame(bmp);
            DImage img = OpenImage(bmp);
            img.IsVideo = true;
        }

        private void FaceDetection()
        {
            Bitmap bmp = ImageList[currImage].ImageBitmap;

            BitmapData bmpd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            int extraBytes = bmpd.Stride - (bmpd.Width * 3);

            PHVideoCapture.DetectFaces((int)bmpd.Scan0, extraBytes);
            bmp.UnlockBits(bmpd);
        }

        private void localStatisticsToolStripMenuItem_Click(object sender, EventArgs e)
        {
          //  string angle = Interaction.InputBox("Please Enter The size of the window", "LocalStatistics", "0");
            matoper3.Class1 matclass = new matoper3.Class1();
            imageList[currImage].UpdateImage(MatlabOperations.LocalStatistics(matclass, imageList[currImage], 3,4f,0.4f,0.02f,0.4f));
        }
    }
}